UICollectionViewのセルを長押しした時に任意のアクションを起動する方法を実装しました。
view読み込み時にジェスチャを設定
override func viewDidLoad() {
super.viewDidLoad()
/// ロングタップ
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(onLongPressAction))
longPressRecognizer.allowableMovement = 10
longPressRecognizer.minimumPressDuration = 1
self.collectionView.addGestureRecognizer(longPressRecognizer)
}
アクションの作成
@objc func onLongPressAction(sender: UILongPressGestureRecognizer) {
let point: CGPoint = sender.location(in: self.collectionView)
let indexPath = self.collectionView.indexPathForItem(at: point)
if let indexPath = indexPath {
//何らかの処理
let vc = OrderMenuViewController.instantiate()
let tableListDic = tables.sorted {
(s1, s2) -> Bool in
s1.name.localizedStandardCompare(s2.name) == .orderedAscending
}
vc.table = tableListDic[indexPath.row]
navigationController?.pushViewController(vc, animated: true)
}
}
参考記事
https://qiita.com/john-rocky/items/5ddff918a6f18607c65e
https://ofsilvers.hateblo.jp/entry/uicollectionview-and-long-press