longPressGesture.minimumPressDurationを0に設定して解決し、ユーザーがタップの原点からドラッグした距離を確認します。
ドラッグの最大距離が原点から一定量以上離れている場合はドラッグとして認識します。そうではありません。
ステップ1: collectionViewにlongPressGestureを実装:
longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(MyViewController.handleLongGesture(gesture:)))
longPressGesture.numberOfTapsRequired = 0
longPressGesture.minimumPressDuration = 0
myCollectionView.addGestureRecognizer(longPressGesture)
ステップ2:ドラッグの距離
var startPoint: CGPoint?
var maxDistance: CGFloat?
ステップを計算するクラスの2つの変数を宣言し3ドラッグの起点からの距離の合計を計算する関数を記述します(このメソッドは、次のステップ)
func calculateDistance(from: CGPoint, to: CGPoint) -> CGFloat {
return sqrt(pow((from.x - to.x),2) + pow((from.y - to.y),2))
}
ステップ4:ドラッグ
func handleLongGesture(gesture: UILongPressGestureRecognizer) {
switch(gesture.state) {
case UIGestureRecognizerState.began:
startPoint = gesture.location(in: myCollectionView)
maxDistance = 0
guard let selectedIndexPath = myCollectionView.indexPathForItem(at: gesture.location(in: myCollectionView)) else {
break
}
myCollectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case UIGestureRecognizerState.changed:
maxDistance = max(maxDistance!, calculateDistance(from: startPoint!, to: gesture.location(in: myCollectionView)))
myCollectionView.updateInteractiveMovementTargetPosition(gesture.location(in: gesture.view!))
case UIGestureRecognizerState.ended:
if maxDistance! < CGFloat(10) {
if let selectedIndexPath = myCollectionView.indexPathForItem(at: gesture.location(in: myCollectionView)) {
collectionView(myCollectionView, didSelectItemAt: selectedIndexPath)
}
}
myCollectionView.endInteractiveMovement()
default:
myCollectionView.cancelInteractiveMovement()
}
}
注ハンドル:私たちは、あなたが発生することが好きな機能を確認して、ステップ4の中から私たちのcollectionViewにdidSelectItemAtIndexを呼び出す をそこにはタップで行く。
最小継続時間を長くすると、私はユーザーがいつも長い時間lilを押して通常のタップを押すとドラッグが起きると予想します。 –