简体   繁体   English

通过触摸屏幕隐藏键盘

[英]Hide keyboard by touching the screen

I want to hide the keyboard by touching the view. 我想通过触摸视图来隐藏键盘。 Everybody recommends to use this method, saying there's no need to link or anything else, but is not working. 每个人都建议使用此方法,说不需要链接或其他任何操作,但是不起作用。

The problem is that my method is not called.Is there anything else that should be done? 问题是我的方法没有被调用,还有其他需要做的事情吗?

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

I had trouble with this so use a method that loops through all views seeing if they are textviews and firstResponders. 我对此有麻烦,因此请使用一种遍历所有视图的方法,以查看它们是否为textviews和firstResponders。 Not sure of the structure of a UITextView but you might need to check for that too although it may be covered. 不确定UITextView的结构,但是您可能也需要检查它,尽管它可能已经涵盖了。

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

The best approach is to create a "lock view" which is a UIView that takes over the whole screen once the textField becomesFirstResponder. 最好的方法是创建一个“锁定视图”,它是一个UIView,一旦textField成为FirstResponder,它将接管整个屏幕。 Make sure it's on top of all views (well, besides the textview, of course). 确保它位于所有视图的顶部(当然,除了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];
}

Use UITapGestureRecognizer For Dismiss keyboard. 使用UITapGestureRecognizer来关闭键盘。

Write this code on your viewdidload(). 将此代码写在您的viewdidload()上。

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

and in dismissKeyboard method put this code. 并在dismissKeyboard方法中放置此代码。

-(void)dismissKeyboard
{
    [TextFieldName resignFirstResponder];

}

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

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