Press-and-hold button for “repeat fire”

后端 未结 6 1181
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 10:43

I have referred to countless other questions about a press-and-hold button but there aren\'t many related to Swift. I have one function connected to a button using the touch

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 11:27

    Swift 5+

    Based on rob's answer there is a nicer way to do this now.

    Add the long press gesture recognizer by dragging it on-top of the button in the storyboard and then ...

    Then you can control-drag from the long press gesture recognizer to your code in the assistant editor and add an @IBAction to handle the long press: - Quote from Rob's Answer

    The difference is in the code which is listed below:

    var timer: Timer?
    
    @IBAction func downButtonLongPressHandler(_ sender: UILongPressGestureRecognizer) {
            if sender.state == .began {
                timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: {_ in
                    self.downButtonPressedLogic()
                    self.doCalculations()
                })
            } else if sender.state == .ended || sender.state == .cancelled {
                print("FINISHED UP LONG PRESS")
                timer?.invalidate()
                timer = nil
            }
    }
    

    You no longer need to use NSTimer, you can just use Timer now and you can just put the code for the timer in the block which is much more compact and no need for selectors.

    In my case I had another function that handles the logic for what to do when the downButton was pressed, but you can put your code you want to handle in there.

    You can control the speed of the repeat fire by changing the withTimeInterval parameter value.

    You can change the timing for the timer to start by finding the longPressGesture in your storyboard and changing it's Min Duration value. I usually set mine at 0.5 so that your normal button press actions can still work (unless you don't care about that). If you set it to 0 this will ALWAYS override your normal button press actions.

提交回复
热议问题