Swift如何在uicollectionviewcell的子元素上添加tap手势

时间:2017-08-31 07:47:31

标签: ios swift uicollectionviewcell

我的代码中有一个UICollectionViewcell

let cell = commentSection.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CommentCell

CommentCell我有这个imageview

let likeIcon: UIImageView = {
    let imv = UIImageView()
    imv.image = #imageLiteral(resourceName: "like")
    imv.translatesAutoresizingMaskIntoConstraints = false
    return imv
}()

我尝试在likeIconCommentCell中向cellForItemAt添加点按手势,但点击时没有触发它。如何向子元素添加gestureTapRecognizer细胞?

2 个答案:

答案 0 :(得分:0)

查看代码:

....
    let imageView = UIImageView()
    imageView.isUserInteractionEnabled = true
    let recognizer = UITapGestureRecognizer()
    recognizer.addTarget(self, action: #selector(yourHandleMethod(tapGestureRecognizer:)))
    imageView.addGestureRecognizer(recognizer)
....

func yourHandleMethod(tapGestureRecognizer: UITapGestureRecognizer) {
    print("tap")
}

update()之外调用此方法cellForItem(对于每个单元格)。

...
    cell.update()
...

//单元格内的此方法

func update() {
    let recognizer = UITapGestureRecognizer()
    recognizer.addTarget(self, action: #selector(yourHandleMethod(tapGestureRecognizer:)))
    imageView.addGestureRecognizer(recognizer)
}

答案 1 :(得分:0)

添加 UIImageView 并提供手势识别器会增加开发的复杂性。 如果您需要操作,请使用 UIButton 并在cellForRowAtIndex

中为按钮设置目标操作

您可以将background imageimage设置为 UIButton

最好在UIImage对象中保留已处理的图像并将其指定给UIButton。