【发布时间】:2018-07-01 22:37:20
【问题描述】:
我有一个带有登录屏幕(手机和密码)的 iOS 应用。让我们想象一个案例:
- 用户点击电话号码文本字段和数字键盘出现,视图是键盘。
- 用户填写电话号码并点击密码文本字段,键盘从数字布局更改为标准。
- 用户点击键盘上的返回按钮,键盘关闭,视图关闭。
- 用户点击电话号码文本字段或密码以更多时间进行数据更正
在第 4 阶段,键盘出现,但视图不再显示,当我点击键盘上的返回按钮时,视图甚至下降,屏幕顶部出现黑线。我该如何解决这个问题?在代码中我有这个:
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
在 viewDidLoad 中:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
和
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height/3
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y += keyboardSize.height/3
}
}
}
【问题讨论】: