swift - UITableView 中的 UICollectionView 由于 view.addGestureRecognizer() 未检测到点击

标签 swift uitableview uicollectionview uigesturerecognizer

我有带有嵌入式 UICollectionView 的 UITableView。在第一部分中,有带有 UITextField 的自定义单元格,在第二部分中有 UICollectionView。

当用户点击我正在使用的 UITextField 外部时隐藏键盘

let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(dismissKeyboard))
view.addGestureRecognizer(tap)

func dismissKeyboard(sender: UIGestureRecognizer) {
    view.endEditing(true)
}

正因为如此,正如我所发现的,我的 UICollectionView 无法识别其项目上的点击。如果我删除 view.addGestureRecognizer(tap) 一切正常,但键盘在这种情况下不会隐藏。

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()  //if desired
    return true
} 

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    switch indexPath.section {
    case 0:
        let cell = tableView.dequeueReusableCell(withIdentifier: "ProfileTableViewCell", for: indexPath) as! ProfileTableViewCell

        cell.value.delegate = self // value is my textField
        return cell

    case 1:
        let cell = tableView.dequeueReusableCell(withIdentifier: "WallpaperTableViewCell", for: indexPath) as! WallpaperTableViewCell
            cell.setCollectionViewDataSourceDelegate(dataSourceDelegate: self, index: (indexPath as NSIndexPath).row)
        return cell

    default:
        let cell = UITableViewCell()
        return cell
    }
}

如何解决此问题并在 UICollectionView 中同时使用隐藏键盘和点击识别? 谢谢

为了将 UICollectionView 嵌入到 UITableView 中,我使用了这个示例 https://github.com/DahanHu/DHCollectionTableView

UPD

感谢菲利普·米尔斯

答案非常简单

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

func keyboardWillShow(notification: NSNotification) {
    view.addGestureRecognizer(tap)

}

func keyboardWillHide(notification: NSNotification) {
    view.removeGestureRecognizer(tap)
}

最佳答案

仅在键盘出现时添加手势识别器,并在键盘消失时将其删除。

关于swift - UITableView 中的 UICollectionView 由于 view.addGestureRecognizer() 未检测到点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40726905/

相关文章:

swift - 将距离测量格式设置为公里或英制英里,而不是公制英里

objective-c - 如何调用接受 block 字典作为 Swift 参数的 Objective-C 函数?

ios - UITableView 更新错误的单元格

ios - 为什么 UICollectionView cellForItemat indexpath 会在一开始就为所有单元格调用

swift - 订阅以获取嵌套数组

ios - 将图像旋转超过 180 度

swift - 如何通过自动布局设置 Collection View 的单元格大小

ios - 重新加载 collectionView 时内存泄漏 : Firebase

iphone - 使用 ASIHTTPRequest 的 UITableViewCell 中的 UIImageView 性能

ios - 从 tableView 中选定的行打开 Map AnnotationView