键盘通知



我正在尝试使用键盘扩展从userInfo获取键盘大小。

我加

NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardDidShowNotification, object: nil)

在我的键盘视图控制器中.swiftkeyboardWillShow从未被调用。

首次注册键盘通知

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
    notificationCenter.addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
    super.viewDidDisappear(animated)
    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

然后

func keyboardWillShow(notification: NSNotification) {
    let userInfo = notification.userInfo!
    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().height
}

并且您的身高值为 CGFloat

在viewWillAppear中,您是否添加了self.subscribeToKeyboardNotifications()?只是猜测一下,您的键盘视图控制器是否与显示键盘的视图控制器分开?如果是这样,请在实际 ViewController 的函数中具有 'NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardDidShowNotification, object: nil)

Swift 3.0 中使用以下代码

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(SignUpViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    notificationCenter.addObserver(self, selector: #selector(SignUpViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)
    let notificationCenter = NotificationCenter.default
    notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    notificationCenter.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification) {
    let userInfo = notification.userInfo!
    let keyboardHeight = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
    UIView.animate(withDuration: 0.3) {
        self.constraintBottomBtnNext.constant = keyboardHeight;
    }
    self.view.layoutIfNeeded();
    print(keyboardHeight);
}
@objc func keyboardWillHide(notification: NSNotification) {
    UIView.animate(withDuration: 0.3) {
        self.constraintBottomBtnNext.constant = 0;
    }
    self.view.layoutIfNeeded();
}

最新更新