UIKit: Hide the keyboard without a reference to the currently focused text field
Googling for answers to UIKit or iOS/iPhone programming problems today resembles googling for answers to JavaScript problems. There is so much horribly, horribly broken code out there, being promoted as the way to do things.
Ranting aside, today’s problem is writing your own view controller container, and noticing that focused UI elements don’t dismiss their keyboard in response to viewWillDisappear: or similar. If this was MacOS, or AppStore approval didn’t exist, you’d just do [self.view.window.firstResponder resignFirstResponder]. You can’t do that though, firstResponder is private on window, don’t ask me why. cdyson37 on StackOverflow however, found the public API -[UIView(UITextField) endEditing:]
hidden in a category in UITextField.h, that supposedly looks recursively through the receiver’s children for the first responder, and if found, resigns it. Perfect! A copy-pasteable code snippet for lazy googlers:
[self.view endEditing:YES]
UPDATE! Turns out I’m an idiot. While the above works and is correct, there is a better way. You don’t NEED to have access to the first responder, because you can use a nil targeted action instead, which will walk the responder chain, starting at the first responder. So a MUCH prettier way of hiding the keyboard is:
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
Thanks to BigZaphod for that code snippet. I haven’t used sendAction: since I did Mac coding, before I suddenly became an almost-iOS-only coder in 2008. The responder chain is so handy, I must start using it more in my iOS coding…