在我的 View Controller 中,我订阅了 UIKeyboardWillShowNotification
:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
所以在我的 keyboardWillShow:
方法中,我能够从通知中检索有关键盘的一些信息。但我想要的是获得对调出键盘的实际文本字段的引用。我无法在谷歌中找到如何做到这一点,我怀疑这可能是不可能的,但有人可能知道。如果确实不可能,那么我想知道是否有可能以相反的方式进行 - 通过引用文本字段来获取有关键盘的信息。谢谢
最佳答案
让我强调@iphonic 评论是正确的做法。
You should use
UITextField
delegate functiontextFieldShouldBeginEditing:
任何不足都是错误的:UIKeyboardWillShowNotification
假设软件键盘会出现,这是一个非常危险的假设,并且在各种情况下可能会失败 ,从但不限于蓝牙键盘开始。 在模拟器中尝试 cmd-K。
这是前面提到的 kludge,灵感来自 Get the current first responder without using a private API
func keyboardWillShow() {
let firstResponder = self.findFirstResponder(inView: self.view)
println("keyboardWillShow for \(firstResponder)")
}
func findFirstResponder(inView view: UIView) -> UIView? {
for subView in view.subviews as! [UIView] {
if subView.isFirstResponder() {
return subView
}
if let recursiveSubView = self.findFirstResponder(inView: subView) {
return recursiveSubView
}
}
return nil
}
关于ios - 是否可以获取与键盘关联的文本字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31981533/