I am adding a view having set of images(socialView) inside a collection view cell(having other views also) on which a common click has to be performed. This click should not be same as collection view cell click.
I am thinking of adding UITapGestureRecognizer for socialView everytime in CollectionView delegate method cellForItemAt. But I want to know is it the right way? Moreover, i want to get the indexPath/position on which socialView has been called.
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.socialViewTapped))
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "bidderAuctionCell", for: indexPath) as! BidderAuctionViewCell
cell.socialView.addGestureRecognizer(tapGestureRecognizer)
}
@objc func socialViewTapped() {
// Which item cell's socialview is clicked
}
UPDATE
I have done as per the below suggestions, but i am not able to get where should i add UITapGestureRecognizer in the custom cell. Following is the custom cell which i have created.
class CustomViewCell: UICollectionViewCell {
var index : IndexPath!
var socialViewDelegate : SocialViewDelegate!
@IBOutlet weak var socialView: UIView!
override init(frame: CGRect) {
super.init(frame:frame)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.viewTapped))
socialView.addGestureRecognizer(tapGestureRecognizer)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
}
@objc func viewTapped(){
socialViewDelegate.socialViewTapped(at: index)
}
}
The init function is not being called. I also tried to put in required init, but there the social view is not initialized. So getting crashed
FINAL ANSWER
class CustomViewCell: UICollectionViewCell {
var index : IndexPath!
var socialViewDelegate : SocialViewDelegate!
@IBOutlet weak var socialView: UIView!
override func awakeFromNib() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
socialView.isUserInteractionEnabled = true
socialView.addGestureRecognizer(tapGesture)
}
@objc func handleTap(){
socialViewDelegate.socialViewTapped(at: index)
}
}
protocol SocialViewDelegate {
func socialViewTapped(at index: IndexPath)
}