swift 中单个对象的 NSNotification

NSNotification for single object in swift

我有两个文本字段,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 的时候。

我假设解决这个问题的关键在于这些方法中的对象参数,我目前正在传递 bottomTextField。 Apple's documentation for NSNotificationCenter 表示该参数用于

The object whose notifications the observer wants to receive; that is, only notifications sent by this sender are delivered to the observer.

If you pass nil, the notification center doesn’t use a notification’s sender to decide whether to deliver it to the observer.

我将其解释为我们可以调出一个特定的对象来监听,所以在本例中是 bottomTextField。但是,当我将它们从“nil”更改为“bottomTextField”时,视图不再向上滑动并且 bottomTextField 仍然隐藏。我的解释有误吗?如果没有,我该怎么做才能让它发挥作用?如果我不正确,有没有办法隔离单个对象以使用 NSNotification 监听?

对象应该是nil。不是文本框

在处理程序中检查键盘 "covered" 哪些文本字段

-(void)keyboardHandler:(NSNotufication *)note {

Cgrect keyboardFrame = [note.userInfo[keyboardframe] cgrectvalue]; // dont remember the key name (answering from my phone :)). Check uiapplication header. 

// check which text field is covered and move it

// you may need to convert the rect coordinates using:

cgrect windowFrame = [[[uiapplication sharedapplication] keyWindow] convertRect:textfieldFrame fromView:textfield.superView]];

If (windowFrame is covered by keyboard ...) { 
    Move text field....
}

希望它够清楚....