ios - 当 View 包含 UICollectionView 时,在 UITextField 之外的任何地方隐藏触摸键盘

标签 ios uiviewcontroller uiscrollview uicollectionview first-responder

有一些答案,例如 this , 但在存在 UIScrollViewUICollectionView 的情况下,它不起作用。
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/

相关文章:

ios - UIViewController 转换使用 MVVM+Coordinators 模式

ios - UIViewController 中的 UICollectionView

ios - 如果 subview 正在滚动,则禁用 super View 滚动

swift - UIScrollView 点击按钮不起作用

ios swift 使用 Realm 数据库建模结构

ios - 如何在 Xamarin 中以编程方式创建不规则按钮?

ios - 如何在 Xcode 4 中发布 json 对象?

ios - 如何相互访问我自己的 2 个 iOS 应用程序数据库

iphone - 注意 View 是从 viewController 外部加载的

ios - 为什么 UITableView 和 UIScrollView 的 bounds 属性中的 "Y"值最初是 "-64"?