Swift:通过NSNotificationCenter的键盘观察器不起作用 [英] Swift: Keyboard Observer via NSNotificationCenter doesn't work

查看:84
本文介绍了Swift:通过NSNotificationCenter的键盘观察器不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to implement a simple keyboard observer in my iOS 8 Swift app but it really doesn't work. This is the code im currently using:

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
}

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

Strangely both functions to react to the keyboard are called once after starting the app. Nothing happens when I enter or leave a textfield. What am I doing wrong? And by the way: Is altering a constraint the best solution for changing the size of an image?

我真的很感谢你的帮助!

I really appreciate your help!

推荐答案

调用 NSNotificationCenter()正在实例化一个新的 NSNotificationCenter 每次你打电话。请尝试使用 NSNotificationCenter.defaultCenter()

Calling NSNotificationCenter() is instantiating a new NSNotificationCenter each time you call it. Try using NSNotificationCenter.defaultCenter() instead.

这篇关于Swift:通过NSNotificationCenter的键盘观察器不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆