我试图将我的整个 View 向上移动,以便能够看到用户在文本字段中输入的内容。但是,它第一次完美地工作,正如我所希望的那样。但是,当单击键盘上的返回键(将其关闭),然后单击文本字段时,我将键盘稍微放在文本字段上方,并且没有得到与第一次相同的结果。这是为什么?
这是我的代码:
@IBOutlet weak var commentTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
commentTextField.delegate = self
//Keyboard listeners
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
commentTextField.resignFirstResponder()
return true
}
最佳答案
替换
UIKeyboardFrameBeginUserInfoKey
与
UIKeyboardFrameEndUserInfoKey
关于ios - 出现键盘时尝试移动 View - 一些错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54854872/