传递Cell数据时,向CollectionViewCell添加一个tap事件

时间:2018-02-04 19:23:12

标签: ios swift uicollectionview

我想在我的CollectionViewCell添加点击事件,并将cell与其所拥有的数据一起传递给我。我怎样才能做到这一点? 我应该ViewController还是CollectionViewCell处理此事件?

我的ViewController

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell
    cell.imgImage.image = imageArray[indexPath.row]
    cell.url = "xhini"

    return cell
}

我的CollectionViewCell

class CollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var imgImage: UIImageView!
    var url: String = "url"
}

enter image description here

2 个答案:

答案 0 :(得分:1)

实施UICollectionViewDelegate然后您可以在ViewController中使用以下方法来响应选择单元格:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let image = imageArray[indexPath.row]
    // do stuff with image, or with other data that you need
}

不要忘记设置代理人设置数据源的位置:

collectionView.dataSource = self
// add this line:
collectionView.delegate = self

<强>更新

或者,如果您使用的是故事板,则需要使用故事板进行设置,方法与为dataSource的{​​{1}}设置数据源的方式相同:

enter image description here

更新2

您的tableView手势识别器会取消集合视图的事件,因此要解决这个问题,只需取消注释行tap,它就能正常工作:

tap.cancelsTouchesInView = false

答案 1 :(得分:1)

我看到你在@Milan的上述回答中分享的代码,并找出了原因 您已在{strong> ViewController 的viewDidLoad添加了点按手势:

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

这会导致UICollectionView's didSelectItemAt没有被调用 所以请注释这个代码,它应该工作。
对于这个手势,你必须找到另一种方法