In my view controller I'm subscribed to UIKeyboardWillShowNotification
:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
so in my keyboardWillShow:
method I'm able to retrieve some info about the keyboard from the notification. But what I want is to get the reference to the actual text field which brings the keyboard up. I couldn't find how to do that in google and I suspect it might be impossible, but someone might know. If it is indeed impossible then I would like to know if there's a possibility to make it reverse way - to get the info about the keyboard by having the reference to the text field. Thanks
You can use the autofocus:true property of the TextField: Whether this text field should focus itself if nothing else is already focused. So whenever the widget appears on screen, if theres nothing else with the keyboard focus, the focus will automatically be directed to it, thus opening the keyboard.
An object that displays an editable text area in your interface.
A control that displays an editable text interface. iOS 13.0+ iPadOS 13.0+ macOS 10.15+ Mac Catalyst 13.0+ tvOS 13.0+ watchOS 6.0+
Set the Boolean variable to false, which enables editing in the text field. When someone taps the Done button, isEditing becomes false. Set the Boolean variable to true, which disables editing in the text field.
Let me emphasize that @iphonic comment is the right way to go.
You should use
UITextField
delegate functiontextFieldShouldBeginEditing:
Anything short of that is a kludge: UIKeyboardWillShowNotification
assumes the software keyboard will show up, with is a very dangerous assumption and is likely to fail in all sorts of situations, starting with but not limited to Bluetooth keyboards. Try cmd-K in Simulator.
Here is aforementioned kludge, inspired by 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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With