我尝试通过AVAudioPlayer构建音乐播放器。我的audioPlayer有效!现在我尝试构建一个双功能按钮:
player.currentTime = 0
)(工作)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)后,倒带计时器不会停止。为什么?
答案 0 :(得分:1)
您应该在rewindLongPressAction函数的范围之外定义rewindTimer。使用手势状态.ended再次调用函数时,它不再具有与rewindTimer相同的引用。