2017-03-14 32 views
0
override func viewWillAppear(_ animated: Bool) { 
    super.viewWillAppear(true) 
    keyboardUpNotification() 
    keyboardDownNotification() 
} 

func keyboardUpNotification() { 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) 
    print("keyboard up notification registered") 
} 
func keyboardWillShow(_ notification: Notification) { 
    view.frame.origin.y = 0 - keyboardSize(notification) 
    print("keyboard will show method. \(keyboardSize(notification))") 
} 


func keyboardDownNotification() { 
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) 
    print("keyboard down notification registered") 
} 
func keyboardWillHide() { 
    print("keyboard will hide method") 
    view.frame.origin.y = 0 
} 

我添加了两个通知(键盘向上,向下)。当我触摸返回按钮时,我想让键盘隐藏。但keyboardWillHide()方法没有调用。我错了什么或错过了什么?通知,键盘隐藏

+0

也显示'keyboardWillShow'方法。 –

+0

你是否启用了你的文本的代表fiedl –

+0

我刚刚添加了keyboardWillShow方法。 –

回答

0

第一件事,第一

词根记忆您的视图控制器,确认文本框的委托

class YourViewController: UIViewController, UITextFieldDelegate { 

} 

2.设置自我为文本字段代表

override func viewDidLoad() { 
    super.viewDidLoad() 
    self.yourTextField.delegate = self 
} 

3.实施

func textFieldShouldReturn(_ textField: UITextField) -> Bool { 
    self.yourTextField.resignFirstResponder() 
    return true 
} 
+0

谢谢!有用! –

+0

@ y-kim:很高兴我能帮忙:) –

0

如果y ou正在使用UITextField,设置代理并覆盖此方法:

optional func textFieldShouldReturn(_ textField: UITextField) -> Bool 

当返回键被命中时,会调用此方法。然后你打电话

textField.resignFirstResponder() 

然后键盘将被解雇。