我正在添加一个视图,其中包含一组图片(socialView)
,放在集合视图单元格中(还有其他视图),需要执行一个共同的点击操作。这个点击操作不应该与集合视图单元格的点击相同。
我考虑每次在CollectionView
委托方法cellForItemAt
中为socialView
添加UITapGestureRecognizer
。但我想知道这样做是否正确?此外,我想获取调用socialView
的indexPath/位置。
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
}
更新
我已按以下建议操作,但我不知道在自定义单元格中应该添加UITapGestureRecognizer。以下是我创建的自定义单元格。
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)
}
}
init函数没有被调用。我尝试了加入必要的init,但社交视图没有被初始化,导致崩溃。
最终答案
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)
}