通过NSbutton Swift继续下一个索引

时间:2018-05-04 03:39:45

标签: swift

我正在为我的应用播放Youtube视频使用“下一步”按钮。我希望按钮在每次单击时将索引增加1。但我只能找到关于.startIndex的信息,我无法弄清楚如何继续添加一个。代码在这里:

@IBAction func nextButton(_ sender: NSButton) {
}

@IBOutlet weak var myWebView: WebView!

override func viewDidLoad() {
    super.viewDidLoad()

    let videoCode = ["ufynqs_COF4", "MXqjDRQbibw", "T3JgUT-fa3A"]
    // attempt to add to index
    let i = videoCode.index(videoCode.startIndex, offsetBy: 1)
    print(i)

    let url = URL(string: "https://youtube.com/embed/\(videoCode[i])")
    var request = URLRequest(url: url!)
    request.setValue("https://youtube.com", forHTTPHeaderField: "Referer")
    self.myWebView.mainFrame.load(request)
}

1 个答案:

答案 0 :(得分:1)

您必须将令牌数组移动到类的顶级并创建计数器

let videoCode = ["ufynqs_COF4", "MXqjDRQbibw", "T3JgUT-fa3A"]
var counter = 0

由于加载下一个视频的代码被使用了两次,因此创建一个方法。它会增加(并且回绕到零)计数器。

func loadNextVideo()
{
    let url = URL(string: "https://youtube.com/embed")!.appendingPathComponent(videoCode[counter])
    var request = URLRequest(url: url)
    request.setValue("https://youtube.com", forHTTPHeaderField: "Referer")
    self.myWebView.mainFrame.load(request)
    counter = (counter + 1) % videoCode.count
}

viewDidLoadIBAction中调用方法

override func viewDidLoad() {
    super.viewDidLoad()
    loadNextVideo()
}

@IBAction func nextButton(_ sender: NSButton) {
    loadNextVideo()
}