如果LongPressReconizerState结束,则计划的计时器不会结束

时间:2018-03-07 13:09:43

标签: swift timer avaudioplayer long-press


我尝试通过AVAudioPlayer构建音乐播放器。我的audioPlayer有效!现在我尝试构建一个双功能按钮:

  1. 一次点击:玩家从头开始(player.currentTime = 0)(工作)
  2. Longpess:玩家以0.5秒为单位开始倒带,并结束"倒带过程"如果按钮已释放
  3. 我的代码(摘要)

    var player = AVAudioPlayer()
    @IBOutlet weak var rewindButton: UIButton!
    
    override func viewDidLoad() {
            super.viewDidLoad()
            let tapGesture = UITapGestureRecognizer(target: self, action:    #selector(rewindTapAction))  //Tap function will call when user tap on button
            let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(rewindLongPressAction(_:))) //Long function will call when user long press on button.
            tapGesture.numberOfTapsRequired = 1
            rewindButton.addGestureRecognizer(tapGesture)
            rewindButton.addGestureRecognizer(longGesture)
    } 
    
    @objc func rewindTapAction(){
        print("tapped")
        player.currentTime = TimeInterval(0)
    }
    
    @objc func rewindLongPressAction(_ gestureRecognizer: UILongPressGestureRecognizer){
        print("longpress")
        var rewindTimer : Timer!
    
        if gestureRecognizer.state == .began{
            print("longpress started")
    
            rewindTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { Timer in
                                self.player.currentTime = TimeInterval( self.player.currentTime - 0.5)
                                print("timer")
                            })
    
        }else if gestureRecognizer.state == .ended || gestureRecognizer.state == .cancelled{
            print("longpress ended")
            rewindTimer.invalidate()
        }
    
    }
    




    我的问题是:

    在我释放rewindButton(longpress)后,倒带计时器不会停止。为什么?

1 个答案:

答案 0 :(得分:1)

您应该在rewindLongPressAction函数的范围之外定义rewindTimer。使用手势状态.ended再次调用函数时,它不再具有与rewindTimer相同的引用。