简体   繁体   中英

How to end long press gesture without lifting finger from screen?

I'm trying to end a long press gesture without lifting my finger from the screen. Is that possible in swift?

I'm making an app that lets you record video. The video recording starts when i press down on a button and ends when I lift my finger from the screen. That part works perfectly. What I also want is for the long press gesture to end after 30 seconds if my finger is still pressed on the button. I actually got it to stop recording but the problem is that the long press gesture doesn't actually end when the recording stops.

Here's some of my code:

func stop() {
    let seconds : Int64 = 5
    let preferredTimeScale : Int32 = 1
    let maxDuration : CMTime = CMTimeMake(seconds, preferredTimeScale)
    movieOutput.maxRecordedDuration = maxDuration

    if movieOutput.recordedDuration == movieOutput.maxRecordedDuration {
       movieOutput.stopRecording()
    }
}

func longTap(_ sender: UILongPressGestureRecognizer){
    print("Long tap")

    stop()

    if sender.state == .ended {
        print("end end")
        movieOutput.stopRecording()
    }
    else if sender.state == .began {
        print("begin")
        captureSession.startRunning()
        startRecording()
    }
}

You could try using a timer to do do the canceling of the gesture:

class myController:UIViewController {
var timer:Timer! = nil
var lpr:UILongPressGestureRecognizer! = nil

override func viewDidLoad() {
    super.viewDidLoad()

    lpr = UILongPressGestureRecognizer()
    lpr.minimumPressDuration = 0.5
    lpr.numberOfTouchesRequired = 1
    // any other gesture setup
    lpr.addTarget(self, action: #selector(doTouchActions))
    self.view.addGestureRecognizer(lpr)


}

func createTimer() {
    if timer == nil {
    timer = Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(cancelTrouchFromTimer), userInfo: nil, repeats: false)
    }
}

func cancelTimer() {
    if timer != nil {
    timer.invalidate()
    timer = nil
    }
}

func cancelTrouchFromTimer() {
    lpr.isEnabled = false
    //do all the things
    lpr.isEnabled = true

}

func doTouchActions(_ sender: UILongPressGestureRecognizer) {
    if sender.state == .began {
        createTimer()
    }

    if sender.state == .ended {// same for other states .failed .cancelled {
    cancelTimer()
    }

}

// cancel timer for all cases where the view could go away, like in deInit
 func deinit {
    cancelTimer()
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM