【问题标题】:Hide keyboard by touching the screen通过触摸屏幕隐藏键盘
【发布时间】:2015-04-13 05:30:03
【问题描述】:

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

问题是我的方法没有被调用,还有什么需要做的吗?

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

【问题讨论】:

    标签: ios uiview keyboard uitouch


    【解决方案1】:

    我遇到了这个问题,所以使用一种方法来遍历所有视图,看看它们是否是 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];
            }
        }
    }
    

    【讨论】:

    • 该方法没有被调用。那是我的问题。
    【解决方案2】:

    使用 UITapGestureRecognizer 来关闭键盘。

    在你的 viewdidload() 上写下这段代码。

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

    并在dismissKeyboard方法中放置这段代码。

    -(void)dismissKeyboard
    {
        [TextFieldName resignFirstResponder];
    
    }
    

    【讨论】:

    • 您必须以这种方式指定每个 UITextField,更通用的方法会更好。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2013-06-02
      • 1970-01-01
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      相关资源
      最近更新 更多