LoginSignup
0
0

More than 1 year has passed since last update.

UICollectionViewでcellを長押し

Posted at

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

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0