【问题标题】:NSNotification for single object in swiftswift中单个对象的NSNotification
【发布时间】: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


    【解决方案1】:

    对象应该是nil。不是文本字段

    在处理程序中检查哪些文本字段被键盘“覆盖”

    -(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....
    }
    

    希望它足够清楚......

    【讨论】:

    • 感谢您的回复。我修改了我的代码以检查哪个文本字段是第一响应者,如果它是底部的则移动键盘。现在效果很好。如果不是这样的事情,我仍然对 notificationSender (对象)参数的用途有点模糊(我假设它不起作用,因为它不是发送通知的文本字段) .什么样的东西会发送通知?在什么情况下我可以使用最后一个参数而不是 nil?
    • 如果许多对象在运行时可以发出相同的“通知名称”并且您只想跟踪来自“特定”对象的通知(注册时指定实例是有意义的)。在系统发出通知的情况下,注册到特定对象通常没有附加价值(很多时候它是单例并且实例是明确的)。同样在某些情况下,通知的发射器没有在 NSNotification 对象中附加足够的上下文(可能是 notification.object == nil?),但您需要发布的实例
    • 对于那些不知道如何检查哪个文本字段是第一响应者的人,请检查this stack overflow
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多