【发布时间】:2019-01-14 07:04:25
【问题描述】:
我在一个集合视图单元(也有其他视图)内添加了一个具有images(socialView) 集合的视图,必须对其执行常见的点击。此单击不应与集合视图单元格单击相同。
我正在考虑每次在CollectionView 委托方法cellForItemAt 中为socialView 添加UITapGestureRecognizer。但我想知道这是正确的方法吗?此外,我想获取调用socialView 的索引路径/位置。
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 函数没有被调用。我也尝试放入所需的初始化,但社交视图未初始化。所以崩溃了
最终答案
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)
}
【问题讨论】:
-
@RobertDresler 添加了代码。请检查
-
@JarvisTheAvenger 我已经更新了代码,我无法在自定义类中添加手势
-
您可以通过将 indexPath 传递给您的自定义类来解决它。并将点击委托给您的视图控制器
-
你有没有把这个类添加到cell的XIB中??
-
您尚未将 UIGestureRecognizerDelegate 添加到您的自定义类中
标签: ios swift uicollectionviewcell uitapgesturerecognizer