有一些答案,例如 this , 但在存在 UIScrollView
或 UICollectionView
的情况下,它不起作用。
viewController
上的 touchesBegan
方法永远不会被调用。
在屏幕上,我在顶部有一个 UITextField
。
在其下方,填满屏幕的其余部分是 UICollectionView
。
如果我触摸 UITextField
以外的任何地方(显然包括 Collection View )
那么最好的方法是什么?
对于这样一个常见的 UI 范例,似乎应该有一个众所周知的解决方案,但我还没有遇到过。
最佳答案
要在点击 View 时关闭键盘:将点击手势添加到您的 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];
}
关于ios - 当 View 包含 UICollectionView 时,在 UITextField 之外的任何地方隐藏触摸键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20937204/