If you ever had a text view control in your iPhone program you may know that obvious task made ridiculously hard to do right for no apparent reason. I bet there are must be one, but, if you do as one of the popular books on iPhone development recommend (adding a empty button to cover all your background and dismiss when it get clicked!) you will wonder how wacky is that.
This is a re post from http://iphonedevelopertips.com/cocoa/how-to-dismiss-the-keyboard-when-using-a-uitextview.html so I will not forget :)
Keyboard dismissal is one of the relay dumb thing on iPhone and developers hustle keep coming back. My search for latest techniques to fight this madness brought me to http://iphonedevelopertips.com/cocoa/how-to-dismiss-the-keyboard-when-using-a-uitextview.html and while original post does not provide a proper solution, one of the commenter provided a very elegant solution that may just work for most folks. Here it is:
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
UITouch *touch = [touches anyObject];
if ([textView isFirstResponder] && [touch view] != textView) {
[textView resignFirstResponder];
}
[textView resignFirstResponder];
}
// My comment : If you have several text controls copy/paste/modify a block above and you are DONE!
}
}
Works for me and keyboard is gone when you tap outside without adding button or writing a lot of code.
Win!