UITableViewCell内的UICollectionViewCell无法响应操作

时间:2017-08-17 07:10:14

标签: ios swift uitableview uicollectionview

我正在开发一个项目,在UITableView内部的UITableViewCell内部有一个UICollectionView。我使用XIB作为我的UICollectionViewCell,它包含一个ImageView,另一个XIB用于我的UITableViewCell,它包含一个UICollectionView。我已设法显示所需的东西,但是,我的自定义集合视图单元格没有响应任何触摸事件。经过一番研究,我试过了:

  • 关闭"启用用户交互"在UITableView&在界面生成器中以编程方式启用UITableViewCell,同时启用"用户交互启用"在UICollectionView和UICollectionViewCell
  • 在UITableViewCell中设置UICollectionView的委托,我的自定义UITableViewCell类实现UICollectionViewDelegate和UICollectionViewDataSource

     collectionView.delegate = self
     collectionView.dataSource = self
    
  • 使用UICollectionView的委托方法

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // my implementation here
    }
    
  • 为cellForItemItemAt中的每个单元格添加自定义UITapGestureRecognizer

     let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(MyCustomTableViewCell.cellTapped))
     tapRecognizer.numberOfTapsRequired = 1
     cell.addGestureRecognizer(tapRecognizer) 
    
  • 使用UITableViewCell,UICollectionView和UICollectionViewCell的自定义实现,覆盖hitTest函数

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        if let hitView = super.hitTest(point, with: event) {
            if hitView is MyCustomCollectionViewCell {
                print("hitTest - MyCustomCollectionViewCell")
                return hitView
            } else {
                return nil
            }
        } else {
            return nil
        }
    }
    

以下是我的自定义TableViewCell XIB的屏幕截图: enter image description here

感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

可能你说错了。 应为tableView,tableViewCell,collectionView,collectionViewCell启用用户交互。如果您将其转换为tableView - 那么其中的所有内容都不会是交互式的。 在这里查看我的示例项目: https://github.com/1mperial8e/CollectionViewExample

我重新创建了相同的情况 - 在viewViewCell中的单元格中使用imageView的collectionView。没有什么额外的,只是简单的意见。您可以比较设置并查找代码或故事板设置中的问题所在。

您不需要任何敲击手势。 collectionView:didSelectItemAtIndexPath:完美无缺。

答案 1 :(得分:1)

事实证明,TableViewCells现在有contentViews阻止我内部的所有触摸。所以,我只是在我的UITableViewDelegate中使用它 -

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    ....
    cell.contentView.isUserInteractionEnabled = false
    ....
}

供参考:can't click UIButton inside a cell in UITableview

向Stas Volskiy致敬,非常乐于助人

相关问题