gpt4 book ai didi

ios - swift 中单个对象的 NSNotification

转载 作者:可可西里 更新时间:2023-11-01 02:19:12 26 4
gpt4 key购买 nike

我有两个文本字段,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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com