Swift:通过NSNotificationCenter的键盘观察器不起作用

我正在尝试在我的iOS 8 Swift应用程序中实现一个简单的键盘观察器,但它确实不起作用。 这是我目前正在使用的代码:

override func viewDidAppear(animated: Bool) { NSNotificationCenter().addObserver(self, selector: Selector(keyboardWillAppear()), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter().addObserver(self, selector: Selector(keyboardWillHide()), name: UIKeyboardWillHideNotification, object: nil) } override func viewDidDisappear(animated: Bool) { NSNotificationCenter().removeObserver(self) } func keyboardWillAppear() { logoHeightConstraint.constant = 128.0 } func keyboardWillHide() { logoHeightConstraint.constant = 256.0 } 

奇怪的是,在启动应用程序后,两个对键盘作出反应的函数都会被调用。 当我进入或离开文本字段时没有任何反应。 我究竟做错了什么? 顺便说一下:改变约束是改变图像大小的最佳解决方案吗?

我非常感谢你的帮助!

每次调用NSNotificationCenter()调用NSNotificationCenter()都会实例化一个新的NSNotificationCenter 。 请尝试使用NSNotificationCenter.defaultCenter()

 //keyboard observers NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil) func keyboardWillAppear() { println("Keyboard appeared") } func keyboardWillHide() { println("Keyboard hidden") } 

我更喜欢使用UIKeyboardWillChangeFrameNotification,因为如果大小发生变化,您会收到通知,例如,当隐藏/显示建议时

 //keyboard observers NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillChange), name: UIKeyboardWillChangeFrameNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(keyboardWillHide), name: UIKeyboardWillHideNotification, object: nil) func keyboardWillChange(notification:NSNotification) { print("Keyboard size changed") } func keyboardWillHide(notification:NSNotification) { print("Keyboard hidden") } 

Swift 4.0,闭包😍:

 NotificationCenter.default.addObserver(forName: .UIKeyboardDidShow, object: nil, queue: nil, using: { notification in // do stuff }) 

Swift 3及以上代码。 添加了获取键盘高度的代码

 func addObservers() { //keyboard observers NotificationCenter.default.addObserver(self, selector: #selector(keyboardDidAppear(notification:)), name: NSNotification.Name.UIKeyboardDidShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil) } @objc func keyboardDidAppear(notification: NSNotification) { print("Keyboard appeared") let keyboardSize:CGSize = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.size print("Keyboard size: \(keyboardSize)") let height = min(keyboardSize.height, keyboardSize.width) let width = max(keyboardSize.height, keyboardSize.width) print(height) print(width) } @objc func keyboardWillHide(notification: NSNotification) { print("Keyboard hidden") }