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

时间:2019-02-24 18:03:39

标签: ios swift uitextfield nsnotificationcenter uikeyboard

我正在尝试将整个视图向上移动,以便能够看到用户在文本字段中键入的内容。但是,它第一次按我的意愿完美运行。但是,当单击键盘上的返回键(将其关闭),然后单击文本字段时,我将键盘稍微移到文本字段上方,而得到的结果却与第一次相同。为什么会这样?

这是我的代码:

@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
}    

2 个答案:

答案 0 :(得分:2)

替换

UIKeyboardFrameBeginUserInfoKey

使用

UIKeyboardFrameEndUserInfoKey

答案 1 :(得分:1)

您正在误调用变量。

UIKeyboardFrameBeginUserInfoKey

  

包含CGRect的NSValue对象的键,该CGRect标识了   屏幕坐标中键盘的起始帧矩形。的   框架矩形反映了设备的当前方向。

UIKeyboardFrameEndUserInfoKey

  

包含CGRect的NSValue对象的键,该CGRect标识了   屏幕坐标中键盘的 end 边框矩形。的   框架矩形反映了设备的当前方向。

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

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

相关问题