现在,我在collectionview单元格中有一堆消息。 我现在点击单元格的代码是
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Which cell: ", indexPath)
}
如何使它仅在双击时才能打印?
答案 0 :(得分:1)
您可以在集合视图中添加UITapGestureRecognizer。
private var doubleTapGesture: UITapGestureRecognizer!
func setUpDoubleTap() {
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapCollectionView))
doubleTapGesture.numberOfTapsRequired = 2
collectionView.addGestureRecognizer(doubleTapGesture)
doubleTapGesture.delaysTouchesBegan = true
}
从您的 viewDidLoad 以上述方式调用
override func viewDidLoad() {
super.viewDidLoad()
setUpDoubleTap()
}
然后在您的课程中添加Gesture选择器方法
@objc func didDoubleTapCollectionView() {
let pointInCollectionView = doubleTapGesture.location(in: collectionView)
if let selectedIndexPath = collectionView.indexPathForItem(at: pointInCollectionView) {
let selectedCell = collectionView.cellForItem(at: selectedIndexPath)
// Print double tapped cell's path
print("Which cell: ", selectedIndexPath.row)
print(" double tapped")
}
}
didDoubleTapCollectionView 方法仅在您双击集合视图单元格项目时才会调用。
我希望以上示例能够解决您的问题。
答案 1 :(得分:0)
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as! customCell
let tapCell = UITapGestureRecognizer(target: self, action: #selector(self.doubleTap(selectedIndex:)))
tapCell.numberOfTapsRequired=2
cell.tag=indexPath.row
cell.addGestureRecognizer(tapCell)
return cell
}
@objc func doubleTap(gesture: UITapGestureRecognizer){
print("Selected Index Is", gesture.view?.tag)
}