ios - swift 中单个对象的 NSNotification

标签 ios swift uitextfield nsnotification virtual-keyboard

我有两个文本字段,topTextField 和 bottomTextField,分别位于屏幕的顶部和底部。 bottomTextField 在出现时隐藏在虚拟键盘后面,以便修复我正在使用 NSNotification 来监听虚拟键盘并在发生这种情况时向上滑动 View 。但是,每当键盘出现在屏幕上时, View 就会向上滑动,包括当 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”时, View 不再向上滑动并且 bottomTextField 仍然隐藏。我的解释有误吗?如果没有,我该怎么做才能让它发挥作用?如果我不正确,有没有办法隔离单个对象以使用 NSNotification 监听?

最佳答案

对象应该是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....
}

希望它够清楚....

关于ios - swift 中单个对象的 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32337888/

相关文章:

swift - 将 ErrorType 转换为 NSError 会丢失关联对象

ios - 检测是否在 UITextField 中插入了一个字符

swift - 如何在 swift 中执行逻辑 XOR 运算以找出所有文本字段是空还是满?

iphone - UIbutton 宽度和高度为零?

ios - 按名称搜索 Unicode 代码点

ios - UICollectionView 和滚动程序错误

ios - 我正在尝试实现一个可视化触摸的简单库。我不知道如何将它集成到我的项目中

swift - Segue 在传递数据时移动得太快?

ios - 在 ViewController Swift 3 中添加 UITabBar(不实现 UITabBarController)

ios - Xcode 10 Crashlytics 安装