2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

長押し続けている間繰り返し処理をするLongPressGestureRecognizer

Posted at

UILongPressGestureRecognizer + Timerで

押し続けている間、連続で処理をするボタンをつくりたい。
たとえば、押している間ミサイルを連写するとか。
UILongPressGestureRecognizerの state.beganでタイマーのリピート処理を始め、 state.endedで Timer.invalidate( ) することで実現できます。

@objc func repeateWhilePressing(_ gestureRecognizer : UILongPressGestureRecognizer){
        switch gestureRecognizer.state {
            case .began:
        print("shot!")//短いタップでも反応するようにここにも処理を書いておきます。

        pressTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { (Timer) in
                       print("shot!")//押している間0.1秒間隔で繰り返し。
                   })
               case .ended:
                   pressTimer?.invalidate()
               default:
                   break
               }
    }

短いタップの場合も反応するように、Long Pressの最小プレス時間を小さく設定。

let longPress = UILongPressGestureRecognizer(target: self, action: #selector(repeateWhilePressing()))
longPress.minimumPressDuration = 0.01

押している間の結果

shot!
shot!
shot!
shot!
shot!


Core MLを使ったアプリを作っています。
機械学習関連の情報を発信しています。

Twitter
[MLBoysチャンネル]
(https://www.youtube.com/channel/UCbHff-wfjTnB3rtXIP6y0xg)
Medium

相棒
note

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?