【问题标题】:Hide keyboard on touch anywhere outside UITextField when view includes UICollectionView当视图包含 UICollectionView 时,在 UITextField 之外的任何地方隐藏触摸键盘
【发布时间】:2014-01-23 02:29:08
【问题描述】:

那里有一些答案,例如this,但在存在UIScrollViewUICollectionView 的情况下,它不起作用。
viewController 上的 touchesBegan 方法永远不会被调用。

在屏幕上,我在顶部有一个UITextField
在此之下,填满屏幕其余部分的是UICollectionView
如果我触摸 UITextField 以外的任何地方,我需要关闭键盘(显然包括集合视图

那么最好的方法是什么?

对于这样一个常见的 UI 范例,似乎应该有一个众所周知的解决方案,但我还没有遇到过。

【问题讨论】:

标签: ios uiviewcontroller uiscrollview uicollectionview first-responder


【解决方案1】:

要在点击视图时关闭键盘:向 ViewController.collectionView 添加一个点击手势,如下所示:

//declare a property to store your current responder
@property (nonatomic, assign) id currentResponder;
//in viewDidLoad:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resignOnTap:)];
    [singleTap setNumberOfTapsRequired:1];
    [singleTap setNumberOfTouchesRequired:1];
    [self.collectionView addGestureRecognizer:singleTap];


//Implement the below delegate method:

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.currentResponder = textField;
}

//Implement resignOnTap:

- (void)resignOnTap:(id)sender {
    [self.currentResponder resignFirstResponder];
}

【讨论】:

  • 如果用户点击集合视图,这将起作用,但我希望有一个更通用的解决方案,用于键盘外的任何触摸。
  • 我认为没有其他简单的方法。任何你必须在这里实现手势识别的方法。让我知道我的回答是否有用..:)
【解决方案2】:

简单的方法是:

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

【讨论】:

    【解决方案3】:

    这是一个更好的解决方案,它不需要为所有内容单独添加手势识别器。它在 Swift 中,但可以很容易地转换为 ObjC。

    将以下内容添加到您的 viewDidLoad() 中:

    let tap = UITapGestureRecognizer(target: self, action: "dismissKeyboard")
    tap.cancelsTouchesInView = false
    view.addGestureRecognizer(tap)
    

    然后添加以下方法声明:

    func dismissKeyboard()
    {
        view.endEditing(true)
    }
    

    ...view 是您的文本字段。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-23
      • 2013-01-22
      • 2015-11-23
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-02-16
      • 2015-01-06
      相关资源
      最近更新 更多