【发布时间】:2014-07-28 16:18:12
【问题描述】:
我试图在我的 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()?