我有一个 UITableViewController
,其中有一堆自定义单元格,其中有一个 playButton
。在 cellForRowAtIndexPath
中,我分配了一个等于按钮的 indexPath
的标签,这样当按下 playButton
时,我设置了按钮的标题为“停止”。它会更改为“停止”,正如它应该的那样,当我按“停止”时,它会更改回“播放”。
我遇到的困难是当我的声音在没有用户干预的情况下自行停止播放时。我设置了一个观察者来监听 MP3 播放器的完成情况。我在 MyTableViewController
的 viewDidLoad
中添加了一个观察者:
以下是我用来更改单元格中 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)
这是我在 MyTableViewController
上的 playMP3
方法:
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
类中,这是我用来发布已完成通知的委托(delegate)方法:
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?
}
最佳答案
您有很多代码,与您上面提到的问题无关。如果我理解您的问题是您不知道如何更新观察者选择器 resetPlayButton()
中的按钮。该按钮位于表格 View 单元格中,并且您已将索引存储在 indexPathOfPlayButton
中。
您可以获得这样的单元格:
let cell: YourCellClass = tableView.cellForIndexPath(NSIndexPath(forItem: indexPathOfPlayButton, inSection: 0))
获取单元格后,您可以更新其输出。
另一种方法是调用reloadData()
关于ios - 发布 NSNotification 时更新自定义单元 UIButton 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33284392/