我正在使用Jukebox庫開發音樂播放器。它有一個代表團,當歌曲持續時間/當前時間等發生變化時提醒元素。在Jukebox示例中,所有的代碼都在ViewController中。因此,例如當前時間更改時,它也會更改滑塊值。我想創建一個可以被多個ViewController使用的播放器類。當我把這個模型類中的委託方法。我如何在ViewController類中訪問它們?接收不同類中的代理方法
第一個屏幕截圖是第一個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](https://stackoverflow.com/questions/6168919/how-do-i-set-up-a-simple-delegate-to-communicate-between-two-view-controllers)示例委託實施。 – Akhilrajtr
這不是我正在尋找。在我的例子中,當歌曲當前時間改變時,委託方法每次都在調用。我需要在secondviewcontroler – eonr
@eonr中查看該庫中的示例 –