我有一个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