09 Dec 2011

How to,在iOS中点击文本框以外区域,隐藏键盘

当点击文本框以外部分时,隐藏键盘,实现很简单,加个Category就可以了,代码如下:

#import <UIKit/UIKit.h>
@interface UITextField (HideKeyBoard)
-(void)hideKeyBoard:(UIView *)view;
@end

#import "UITextField+HideKeyBoard.h"

@implementation UITextField (HideKeyBoard)
- (void) hideKeyBoard:(UIView*)view{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(doHideKeyBoard)];
   
    tap.numberOfTapsRequired = 1;
    [view  addGestureRecognizer: tap];
    [tap setCancelsTouchesInView:NO];
    [tap release];
}

- (void)doHideKeyBoard{
    [self resignFirstResponder];
}
@end

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.txtInput hideKeyBoard:self.view];
}

see also: https://gist.github.com/1450404