我有一个UICollectionView,我在其中启用了拖动项目。但我还需要能够检测到物品上的水龙头。
要检测点击,我只需使用didSelectItemAtIndex
为了检测拖动,我已经在collectionView中添加了一个UILongPressGestureRecognizer,并从长按的位置找到了单元格:
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(OrganizeWidgetsViewController.handleLongGesture(gesture:)))
longPressGesture.numberOfTapsRequired = 0
longPressGesture.minimumPressDuration = 0.01
widgetCollectionView.addGestureRecognizer(longPressGesture)
问题在于,当用户的手指触摸屏幕并开始拖动时,我需要立即进行拖动。但是,我的longPressGestrue的低minimumPressDuration(为0.01)可以防止检测到水龙头。
我的longPressGesture被检测到,但水龙头通常没有。有没有更好的方法来检测单击和启用单元格拖动?
答案 0 :(得分:1)
我通过将 longPressGesture.minimumPressDuration 设置为0来解决此问题,然后检查用户从点按源拖动的距离。
如果拖动距离原点的最大距离大于一定量,我将其识别为拖动。不过,这是一个轻拍。
第1步:将longPressGesture实现到collectionView:
out:
a
b
4 1
6 3
nan 2
第2步:在类上声明两个变量来计算拖动距离
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(MyViewController.handleLongGesture(gesture:)))
longPressGesture.numberOfTapsRequired = 0
longPressGesture.minimumPressDuration = 0
myCollectionView.addGestureRecognizer(longPressGesture)
第3步编写一个函数,计算远离拖动原点的总距离(我们将在下一步中使用此方法)
var startPoint: CGPoint?
var maxDistance: CGFloat?
第4步:处理拖动
func calculateDistance(from: CGPoint, to: CGPoint) -> CGFloat {
return sqrt(pow((from.x - to.x),2) + pow((from.y - to.y),2))
}
注意:强> 我们在第4步中调用了我们的collectionView上的didSelectItemAtIndex,因此请确保您想要在其中执行任何功能。