我正在尝试在我的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.defaultCenter()
吗? - Patrick Goley