我正在构建一个原型播放器应用程序,使我可以向前和向后跳过。问题是当我跳到很远或按上一个按钮多次导致应用程序由于“索引超出范围”而崩溃时。我尝试了很多事情,但无法解决此问题。这是我的代码。谢谢!
let player = AVPlayer()
var urlPlayerItems = [String]()
var currentTrack: Int = 0
@IBAction func didTapPreviousButton(_ sender: UIButton) {
if (currentTrack - 1) < 0 {
currentTrack = (urlPlayerItems.count - 1) < 0 ? 0 : (urlPlayerItems.count - 1)
} else {
currentTrack -= 1
}
playTrack()
}
@IBAction func didTapNextButton(_ sender: UIButton) {
if (currentTrack + 1) > urlPlayerItems.count {
currentTrack = 0
} else {
currentTrack += 1
}
playTrack()
}
最佳答案
let player = AVPlayer()
var urlPlayerItems = [String]()
var currentTrack: Int = 0
@IBAction func didTapPreviousButton(_ sender: UIButton) {
if currentTrack >= 1 {
currentTrack -= 1
}
playTrack()
}
@IBAction func didTapNextButton(_ sender: UIButton) {
if currentTrack <= urlPlayerItems.count - 2 {
currentTrack += 1
}
playTrack()
}