點擊除了TextField的任何位置收鍵盤

點擊空白和任意控件收鍵盤,第一次用.swift

    

- (void)viewDidLoad
{
    [super viewDidLoad];
  
  [self setUpForDismissKeyboard];
}
- (void)setUpForDismissKeyboard {  
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
  UITapGestureRecognizer *singleTapGR =
  [[UITapGestureRecognizer alloc] initWithTarget:self
                                          action:@selector(tapAnywhereToDismissKeyboard:)];
  NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
  __weak typeof(self) weakSelf = self; 
  [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];
}
//4月5日修改
-(void)viewWillDisappear:(BOOL)animated
{
//觀察者回收,否則dealloc會出錯
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

 

4月5日更新修改,實際使用過程當中發現block裏self此處須要__weak修飾.app

須要回收觀察者,否則dealloc會出錯.ide

本文轉帖,來源已註明.code

相關文章
相關標籤/搜索