Thursday, May 12, 2011

Tap Background to Dismiss Keyboard for UITextViews

I found Apple didn't treat UITextView very well, they didn't provide "done" button in its keyboard. There are a lot of tutorials taught to listen "return" key stroke to dismiss the keyboard. However, I think this is very unwise since UITextView is supposed to carry multiply lines. Therefore, I will show you a better way to dismiss keyboard.

Basically, what I'm going to do is add an invisible view and recognize tap on this view using UITapGestureRecognizer. The trick is don't forget to send this view to the back. So the UITapGestureRecognizer will not intercept tapping on the UITextViews.

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;

    //view to catch  tap
    UIView *view = [[UIView alloc] init];

    //leave the navigation bar alone
    view.frame = CGRectMake(0, 60, screenWidth, screenHeight-60);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                        action:@selector(dismissKeyboard)];
    
    [view addGestureRecognizer:tap];
    
    [self.view addSubview:view];
    [self.view sendSubviewToBack:view];
    


The rest is easy. In my projects, there are two UITextViews so I need more code to checkt which one is the firstResonder.

-(void)dismissKeyboard {
   
    
    if([text1 isFirstResponder])[text1 resignFirstResponder];
    
    if([text2 isFirstResponder])[text2 resignFirstResponder];
}


2 comments:

سـ ع ـود said...

Hi

i have been trying to dismiss the keyboard from my UITextView since 2 days now, i have tried your method and i guess it is the closest solution to what i am trying to do after surfing in google.
tried to apply it on my project. it worked but for some freaking reason when i opened my project today it is not working i dont know what is the problem

Ryan Phelps said...

I have to agree with you that Apple didn't treat UITextView very well. I have followed a lot of tutorials I found online but yours is the best.

membrane switch