出现键盘时尝试移动视图 - 一些错误

Trying to move view when keyboard is appear - some bugs

我试图将整个视图向上移动,以便能够看到用户在文本字段中输入的内容。但是,它第一次完美地工作,正如我所希望的那样。但是,当单击键盘上的 return 键(关闭它),然后单击文本字段时,我将键盘稍微放在文本字段上方,并且没有得到与第一次相同的结果。这是为什么?

这是我的代码:

@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

您错误调用了变量。

UIKeyboardFrameBeginUserInfoKey

The key for an NSValue object containing a CGRect that identifies the starting frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.

UIKeyboardFrameEndUserInfoKey

The key for an NSValue object containing a CGRect that identifies the ending frame rectangle of the keyboard in screen coordinates. The frame rectangle reflects the current orientation of the device.

因此,您需要检查的是 UIKeyboardFrameEndUserInfoKey 而不是 UIKeyboardFrameBeginUserInfoKey。

进行替换,你可能会解决它。