【发布时间】:2017-08-03 11:08:45
【问题描述】:
我正在使用Jukebox 库开发音乐播放器。它有一个委托,当歌曲持续时间/当前时间等发生变化时会警告元素。在 Jukebox 示例中,所有代码都在 ViewController 中。因此,例如当当前时间改变时,它也会改变滑块值。我想创建一个可供多个 ViewController 使用的播放器类。当我将委托方法放在这个模型类中时。如何在 ViewController 类中访问它们?
First Screenshot 是第一个具有委托方法和初始化播放器的 ViewController。
MainViewController 我需要在 secondViewController 中访问该委托方法来更新 UI。
class ViewController: UIViewController, JukeboxDelegate {
var jukebox : Jukebox!
override func viewDidLoad() {
super.viewDidLoad()
configureUI()
// begin receiving remote events
UIApplication.shared.beginReceivingRemoteControlEvents()
// configure jukebox
jukebox = Jukebox(delegate: self, items: [
JukeboxItem(URL: URL(string: "http://www.kissfm.ro/listen.pls")!),
JukeboxItem(URL: URL(string: "http://www.noiseaddicts.com/samples_1w72b820/2514.mp3")!),
JukeboxItem(URL: URL(string: "http://www.noiseaddicts.com/samples_1w72b820/2958.mp3")!)
])!
}
// MARK:- JukeboxDelegate -
func jukeboxDidLoadItem(_ jukebox: Jukebox, item: JukeboxItem) {
print("Jukebox did load: \(item.URL.lastPathComponent)")
}
func jukeboxPlaybackProgressDidChange(_ jukebox: Jukebox) {
if let currentTime = jukebox.currentItem?.currentTime, let duration = jukebox.currentItem?.meta.duration {
let value = Float(currentTime / duration)
slider.value = value
populateLabelWithTime(currentTimeLabel, time: currentTime)
populateLabelWithTime(durationLabel, time: duration)
} else {
resetUI()
}
}
func jukeboxStateDidChange(_ jukebox: Jukebox) {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.indicator.alpha = jukebox.state == .loading ? 1 : 0
self.playPauseButton.alpha = jukebox.state == .loading ? 0 : 1
self.playPauseButton.isEnabled = jukebox.state == .loading ? false : true
})
if jukebox.state == .ready {
playPauseButton.setImage(UIImage(named: "playBtn"), for: UIControlState())
} else if jukebox.state == .loading {
playPauseButton.setImage(UIImage(named: "pauseBtn"), for: UIControlState())
} else {
volumeSlider.value = jukebox.volume
let imageName: String
switch jukebox.state {
case .playing, .loading:
imageName = "pauseBtn"
case .paused, .failed, .ready:
imageName = "playBtn"
}
playPauseButton.setImage(UIImage(named: imageName), for: UIControlState())
}
print("Jukebox state changed to \(jukebox.state)")
}
func jukeboxDidUpdateMetadata(_ jukebox: Jukebox, forItem: JukeboxItem) {
print("Item updated:\n\(forItem)")
}
【问题讨论】:
-
参见this 示例委托实现。
-
这不是我要找的。在我的示例中,当歌曲当前时间更改时,委托方法每次都会调用。我需要在 secondviewcontroler 中使用该方法
-
@eonr 查看该库中的示例
-
@Ramesh 我添加了。