强制键盘隐藏

在网上查找了很多方法,看了很多帖子,现在总结一下。

目标:在不需要输入的地方隐藏键盘

方法:利用手势功能,当点击的地方不是UITextField之类的地方时,自动隐藏键盘。

代码:

1,在UIViewController中实现UIGestureRecognizerDelegate,并声明一个变量

@interface MainViewController : CDVViewController<UIGestureRecognizerDelegate>{

    UITapGestureRecognizer *tapRecognizer;

}


@end

2,在viewDidLoad中加入代码。

//键盘将要出现时的触发事件

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

    tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard:)];

    

    // single tap to resign keyboard    

    tapRecognizer.numberOfTapsRequired = 1;

    tapRecognizer.cancelsTouchesInView = NO;

    tapRecognizer.delegate = self;

    self.webView.userInteractionEnabled = YES;

    [self.webView addGestureRecognizer:tapRecognizer];


3,分别实现所需要的方法


-(void)keyboardWillShow:(NSNotification*)notification{

    self.webView.scrollView.scrollEnabled=NO;

    

    [self.view addGestureRecognizer:tapRecognizer];

}


-(void)keyboardWillHide:(NSNotification*)notification{

    self.webView.scrollView.scrollEnabled=YES;

    

    [self.view removeGestureRecognizer:tapRecognizer];

}


- (void)hideKeyBoard: (UITapGestureRecognizer*) recognizer {

    NSLog(@"hideKeyBoard");

    [self.webView endEditing:YES];//强制隐藏键盘

}

手势必须要编写的代理方法

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer

{

    return YES;

}



你可能感兴趣的:(强制键盘隐藏)