据我了解object
,该方法的参数addObserver
是您要从中接收通知的对象。大多数时候我认为它是nil
(我认为这是因为所有对象都需要指定类型的通知)。在我的特殊情况下,我在屏幕顶部和屏幕底部有一个文本字段,我希望视图仅在用户点击底部文本字段时向上移动,而不是顶部。所以我调用以下方法viewWillAppear
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: self.bottomTextField)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: self.bottomTextField)
}
和选择keyboardWillShow:
器keyboardWillHide:
调用重新定位视图框架的方法。我尝试将object
参数保留为,nil
但这会从两个文本字段接收通知。我尝试将object
参数设置为self.bottomTextField
(如上所示),但没有收到来自任一文本字段的通知。我的问题是双重的。首先,我addObserver
是否正确理解了该方法(尤其是object
参数),其次,为什么它没有从self.bottomTextField
. 谢谢!
解决方案: 我知道这不是我所问的确切问题的解决方案,但我最终在仅单击底部文本字段时使视图向上移动的操作如下:
func subscribeToKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
然后在keyboardWillShow:
我的方法中:
func keyboardWillShow(notification: NSNotification) {
if bottomTextField.editing { // only reset frame's origin if editing from the bottomTextField
view.frame.origin.y -= getKeyboardHeight(notification)
}
}
希望这会有所帮助!