触摸屏幕隐藏键盘

时间:2015-02-12 13:01:31

标签: ios uiview keyboard uitouch

我想通过触摸视图来隐藏键盘。每个人都建议使用这种方法,说不需要链接或其他任何东西,但是不起作用。

问题是我的方法没有被调用。还有什么应该做的吗?

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

3 个答案:

答案 0 :(得分:2)

我遇到了麻烦,所以请使用一种循环遍历所有视图的方法,看看它们是textview还是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];
        }
    }
}

答案 1 :(得分:1)

最好的方法是创建一个"锁定视图"这是一个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];
}

答案 2 :(得分:0)

使用UITapGestureRecognizer解除键盘。

将此代码写在viewdidload()上。

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

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

-(void)dismissKeyboard
{
    [TextFieldName resignFirstResponder];

}
相关问题