我有一個UITableViewController
與一堆自定義單元格中有一個playButton
。在cellForRowAtIndexPath
中,我分配了一個標籤,該標籤等於按鈕的indexPath
,以便按下playButton
時,我將按鈕的標題設置爲「停止」。它會更改爲「停止」,因爲它應該,而當我按下「停止」時,它會變回「播放」。當NSNotification發佈時更新自定義單元格UIButton標題
我遇到困難的時候我的聲音停止播放,沒有用戶干預。我建立了一個觀察者來聽MP3播放器的完成。我加入viewDidLoad
MyTableViewController
的觀察員:
這裏是變量我使用的方便改變playButton
的標題在我的細胞:
// Variables to facilitate changing playButton title
var indexPathOfPlayButton = Int()
var isPlaying: Bool = false
在MyTableViewController
viewDidLoad
,我添加此觀察者:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "resetPlayButton", name: resetPlayButtonNotification, object: nil)
這裏是我的playMP3
方法上MyTableViewController
:
func playMP3(sender: AnyObject) {
if isPlaying == false {
isPlaying = true
// This gets the indexPath of the button that sent the playMP3 request
let indexPath = sender.tag
sender.setTitle("Stop", forState: UIControlState.Normal)
// This sets the indexPath of the playButton that we'll redraw the button when it receives a notification?
indexPathOfPlayButton = indexPath
if resultsSearchController.active {
let soundToPlay = self.filteredSounds[indexPath]
let soundFilename = soundToPlay.soundFilename as String
mp3Player = MP3Player(fileName: soundFilename)
mp3Player.play()
} else {
let soundToPlay = self.unfilteredSounds[indexPath]
let soundFilename = soundToPlay.soundFilename as String
mp3Player = MP3Player(fileName: soundFilename)
mp3Player.play()
}
}
else if isPlaying == true {
isPlaying = false
sender.setTitle("Play", forState: UIControlState.Normal)
mp3Player.stop()
}
}
在我MP3Player
類,這是委託方法我使用後,它的完成通知:
func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
if currentTrackIndex == tracks.count - 1 {
print("end of playlist reached")
player.stop()
NSNotificationCenter.defaultCenter().postNotificationName(resetPlayButtonNotification, object: self)
}
else if flag == true {
print("advance to next track")
nextSong(true)
}
}
最後,這是當一個通知發佈時調用上MyTableViewController
方法:
func resetPlayButton() {
print("resetPlayButtonCalled")
// TODO: How do I get a hold of the button and change the title from outside playMP3?
}
謝謝您的迴應。我想到了。我沒有在'playMP3'中設置indexPath變量,而是在該類中添加了一個按鈕變量,並將其設置爲'playMP3'。 – Adrian