我正在尝试在我的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
}
奇怪的是,启动应用程序后,两个对键盘作出反应的函数都会被调用。当我进入或离开文本字段时没有任何反应。我究竟做错了什么?顺便说一下:改变约束是改变图像大小的最佳解决方案吗?
我真的很感谢你的帮助!
答案 0 :(得分:8)
每次调用NSNotificationCenter()
时,调用NSNotificationCenter
都会实例化NSNotificationCenter.defaultCenter()
。请尝试使用{{1}}。
答案 1 :(得分:8)
//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")
}
答案 2 :(得分:1)
我更喜欢使用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")
}
答案 3 :(得分:1)
Swift 4.0,关闭:
NotificationCenter.default.addObserver(forName: .UIKeyboardDidShow, object: nil, queue: nil, using: { notification in
// do stuff
})
答案 4 :(得分:0)
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")
}