繁体   English   中英

通过触摸屏幕隐藏键盘

[英]Hide keyboard by touching the screen

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

问题是我的方法没有被调用,还有其他需要做的事情吗?

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

我对此有麻烦,因此请使用一种遍历所有视图的方法,以查看它们是否为textviews和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];
        }
    }
}

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

使用UITapGestureRecognizer来关闭键盘。

将此代码写在您的viewdidload()上。

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

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

-(void)dismissKeyboard
{
    [TextFieldName resignFirstResponder];

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM