[英]How to double tap (instead of a single tap) a collection view cell in swift?
Right now, I have a bunch of messages in a collectionview cell. 现在,我在collectionview单元中有一堆消息。 My code to single tap the cell right now is
我现在单击单元格的代码是
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Which cell: ", indexPath)
}
How do I make it such that this will only print if it is double tapped not single tapped? 我如何使它仅在双击时才能打印?
You can add UITapGestureRecognizer in collection view. 您可以在集合视图中添加UITapGestureRecognizer。
private var doubleTapGesture: UITapGestureRecognizer!
func setUpDoubleTap() {
doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(didDoubleTapCollectionView))
doubleTapGesture.numberOfTapsRequired = 2
collectionView.addGestureRecognizer(doubleTapGesture)
doubleTapGesture.delaysTouchesBegan = true
}
Call above method from your viewDidLoad as 从您的viewDidLoad调用上述方法为
override func viewDidLoad() {
super.viewDidLoad()
setUpDoubleTap()
}
Then add Gesture selector method in your class 然后在您的课程中添加手势选择器方法
@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 method will call only when you will double tap on collection view cell item. didDoubleTapCollectionView方法仅在您双击集合视图单元格项目时才会调用。
I hope above example will solve your problem. 我希望以上示例能够解决您的问题。
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)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.