iOS点击任何空白地方退出键盘

应用场景:登录界面或者填写信息的时候点击空白退出键盘

  • 一般解决方案:
    1.监听scrollView实时滚动代理方法调用[self.view endEditing:YES]或者[self.textField resignFirstResponse];
    2.touchBegin方法里,调用[self.view endEditing:YES]或者[self.textField resignFirstResponse];

这里介绍另外一种解决方案

  • 1.给viewController写一个分类
  • 2.利用键盘弹出和退出发出通知调用相应的方法
  • 3.给当前控制器添加点击手势
@interface UIViewController (DismissKeyboard)
-(void)setupForDismissKeyboard;
@end
@implementation UIViewController (DismissKeyboard)
- (void)setupForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    
    __weak UIViewController *weakSelf = self;
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [weakSelf.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}

用法

  • 1.导入头文件
#import "UIViewController+DismissKeyboard.h"
  • 2.在viewDidLoad方法中主动调用
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupForDismissKeyboard];
}

你可能感兴趣的:(iOS点击任何空白地方退出键盘)