通过触摸屏幕隐藏键盘

Hide keyboard by touching the screen

我想通过触摸视图隐藏键盘。大家都推荐用这个方法,说不用link什么的,但是不行。

问题是我的方法没有called.Is还有什么需要做的吗?

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [[self view] endEditing:YES];
}

我在这方面遇到了麻烦,所以使用一种循环遍历所有视图的方法,看看它们是否是文本视图和 firstResponders。不确定 UITextView 的结构,但您可能也需要检查它,尽管它可能被覆盖。

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    for (UIView *txt in self.view.subviews){
        if ([txt isKindOfClass:[UITextField class]] && [txt isFirstResponder]) {
            [txt resignFirstResponder];
        }
    }
}

使用 UITapGestureRecognizer 关闭键盘。

将此代码写入您的 viewdidload()。

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];[self.view addGestureRecognizer:tap];

并在 dismissKeyboard 方法中放入此代码。

-(void)dismissKeyboard
{
    [TextFieldName resignFirstResponder];

}

最好的方法是创建一个 "lock view",它是一个 UIView,一旦 textField 成为 FirstResponder,它就会接管整个屏幕。确保它位于所有视图之上(当然,除了 textview 之外)。

- (void)loadLockView {
    CGRect bounds = [UIScreen mainScreen].bounds;
    _lockView = [[UIView alloc] initWithFrame:bounds];
    _lockView.backgroundColor = [UIColor clearColor];

    UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lockViewTapped:)];
    [_lockView addGestureRecognizer:tgr];
    [self.view addSubview:_lockView];
}

- (void)lockViewTapped:(UITapGestureRecognizer *)tgr {
     [_lockView removeFromSuperView];
     [_textField resignFirstResponder];
}