しるてく

技術的な話をします

UICollectionViewでCellを長押ししたい

UILongPressGestureRecognizer を都度生成するの効率悪いのでViewDidLoadで一度だけ生成して、タップ後にどのCellを押したか判定する感じにする

     override func viewDidLoad() {
        super.viewDidLoad()

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "onLongPressAction:")
        longPressRecognizer.allowableMovement = 10
        longPressRecognizer.minimumPressDuration = 0.5
        self.collectionView.addGestureRecognizer(longPressRecognizer)
    }
    func onLongPressAction(sender: UILongPressGestureRecognizer) {
        let point: CGPoint = sender.locationInView(self.collectionView)
        let indexPath = self.collectionView.indexPathForItemAtPoint(point)

        if let indexPath = indexPath {
            switch sender.state {
            case .Began:
                // 例えばTimerをstartさせる
            case .Ended:
                // 例えばTimerをstopさせる
            default:
                break
        }
    }