Ready to Level-Up?

This just in! If your rusty iOS skills could use some refining, or if you're just starting out and you want to level-up fast, consider signing up for our upcoming iOS Screencasts

New from iOS Rocket Surgery Swift Video Tutorials: The rapidly evolving Apple-iOS ecosystem has just been thrown into tumult with the recent introduction of the Swift Programming Language. Are you ready to finally try iOS development? Are you needing to switch from Objective-C to Swift? Sign up today for our free video courses!
(By the dear folks at Swift Tutorial Videos, a sister company)

Wednesday, July 24, 2013

Dismissing the iOS Keyboard

So, you want to hide the iOS keyboard when exiting a textfield, huh?


For starters the term you are looking for is "resign first responder". You want your textfield to "resign" from being the "first responder" for input (such as typing) and other events.

This is one of those things that I believe Apple could have handled for you as a built-in convention, but they decided for whatever good reason to make you handle this yourself (as of iOS 7 and prior).

How do you "resign first responder"? Well, I've never seen an implementation of this that I love yet... but most implementations are some twist on overriding the UIView class via a category, and handling taps and other gestures, and the event handler literally iterates over all the child views and asks each textfield to resign as first responder. Yuck, right? Well, this is the state of the art answer I'm afraid.

@implementation UIView (FindAndResignFirstResponder)
- (BOOL)findAndResignFirstResponder
{
    if (self.isFirstResponder) {
        [self resignFirstResponder];
        return YES;  
    }
    for (UIView *subView in self.subviews) {
        if ([subView findAndResignFirstResponder])
            return YES;
    }
    return NO;
}
@end

This is a view category... and basically, you'll need to add a gesture recognizer (probably Tap) on all your controllers that have text fields in order to handle this. I happen to use a common base controller class so, all my controllers inherit this behavior by default.

It isn't pretty, but it does the job... until Apple decides to resolve this for you... which, hopefully they will someday.

Works Sited:
http://stackoverflow.com/questions/1823317/get-the-current-first-responder-without-using-a-private-api


UPDATED: much easier


[self.myTextField addTarget:self action:@selector(textFieldFinished:) forControlEvents: UIControlEventEditingDidEndOnExit];



-(void) textFieldFinished:(id) sender
{
  [sender resignFirstResponder];
}





About Me

Easy NSDateFormatter Tool

Save yourself some time in formatting your NSDates to NSStrings, and use the Blind NSDate app, which you can download from iTunes. There's also a website where you can format your NSDates: http://www.blindnsdate.com

Popular Posts

Designed By Seo Blogger Templates