I have a UICollectionViewcell in my code
let cell = commentSection.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! CommentCell
And in CommentCell
i have got this imageview
let likeIcon: UIImageView = {
let imv = UIImageView()
imv.image = #imageLiteral(resourceName: "like")
imv.translatesAutoresizingMaskIntoConstraints = false
return imv
}()
I tried adding a tap gesture to likeIcon
in CommentCell
and also in cellForItemAt
but none of them triggered it when clicking.How can i add gestureTapRecognizer
to child element of cell?
Look at the code:
....
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")
}
Call this method update()
outside in cellForItem
(for every cell).
...
cell.update()
...
// This method inside cell
func update() {
let recognizer = UITapGestureRecognizer()
recognizer.addTarget(self, action: #selector(yourHandleMethod(tapGestureRecognizer:)))
imageView.addGestureRecognizer(recognizer)
}
Adding UIImageView and providing gesture recognizer will increase the complexity of your development. If you need action then use UIButton and set target action for button in cellForRowAtIndex
You can set either background image
or image
to UIButton .
Better keep processed image in UIImage object and assign it to UIButton.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.