【发布时间】:2015-11-27 01:27:17
【问题描述】:
我有两个文本字段,topTextField 和 bottomTextField,分别位于屏幕的顶部和底部。 bottomTextField 出现时隐藏在虚拟键盘后面,以便修复我正在使用 NSNotification 侦听虚拟键盘并在发生这种情况时向上滑动视图。然而,每当键盘出现在屏幕上时,视图就会向上滑动,包括当 topTextField 成为第一响应者时,有效地将其移出屏幕。代码如下:
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: bottomTextField)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: bottomTextField)
}
func unsubscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: bottomTextField)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: bottomTextField)
}
我最初将“nil”作为方法末尾的对象参数,这是我开始寻找将行为隔离到仅底部文本字段的方法的时候。
我假设解决这个问题的关键是在这些方法中的对象参数中,我目前在其中传入了bottomTextField。 Apple's documentation for NSNotificationCenter 表示该参数用于
观察者想要接收其通知的对象;也就是说,只有此发送者发送的通知才会传递给观察者。
如果你传递 nil,通知中心不会使用通知的发送者来决定是否将它传递给观察者。
我将其解释为我们可以调用一个特定的对象来监听,所以在本例中为底部文本字段。但是,当我将它们从“nil”更改为“bottomTextField”时,视图不再向上滑动并且bottomTextField 仍然隐藏。我是否错误地解释了这一点?如果没有,我该怎么做才能让它发挥作用?如果我不正确,有没有办法用 NSNotification 隔离单个对象来监听?
【问题讨论】:
标签: ios swift uitextfield nsnotification virtual-keyboard