我已经使用https://github.com/jorgenhenrichsen/SwiftAudio这个库在UITableView中添加了音频播放器。播放器工作正常,但在更改UITableView中的播放暂停按钮图像时遇到问题。
这个库有一个提供音频状态的方法(播放,就绪,缓冲区,失败):
func setPlayButtonState(forAudioPlayerState state: AudioPlayerState) ()
此方法效果很好,并且在将音频添加到View Controller中时在播放音频时更改“按钮图像”。但是我必须管理UITableViewCell中的状态。
像这样:
为了更改单元格的按钮图像,我使用了以下方法:
func setPlayButtonState(forAudioPlayerState state: AudioPlayerState) () {
let cell = YOUR_TABLEVIEW_REF.cellForRow(at: IndexPath(row: YOUR_ROW_FOR_LANGUAGE_CELL, section: YOUR_SECTION_FOR_LANGUAGE_CELL)) as! AppSettingViewCell
cell.playButton.image = UIImage(named: "IMAGE NAME")
}
它适用于一个索引。但是我需要做的是单击其他行后再次将其更改为停止状态。
和我的配置单元格方法:
func configurePlaylistCell (tableView: UITableView, cell: PlaylistCell, controller: AudioController, indexPath: IndexPath){
cell.playPauseButton.tag = indexPath.row + 100
cell.playButtonPressed = { [weak self] (sender: UIButton) in
self?.indexPathForCell = IndexPath(row: sender.tag - 100 , section: 0)
if !controller.audioSessionController.audioSessionIsActive {
try? controller.audioSessionController.activateSession()
}
print (controller.player.currentIndex)
if let item = controller.player.currentItem {
if (indexPath.row == 0) {
try? controller.player.load(item: item, playWhenReady: true)
}else {
try? controller.player.jumpToItem(atIndex: sender.tag - 100, playWhenReady: true)
}
}
else {
controller.player.togglePlaying()
}
}
}
最佳答案
您可以将当前播放单元的索引保存在属性中(我们将其称为X)。然后,在另一个单元格中点击该按钮(我们称其为Y),您可以:
这将再次导致状态更改,这次是单元格Y,因此您将更改单元格Y的图标。
附带说明一下,我想警告您,可能您应该将所有单元格的状态保存在某种数据结构(如数组)中,然后使用它来使cellForRowAtIndexPath中的单元格出队,否则当单元格开始时您可能会遇到一些问题超出您在屏幕上看到的内容。
我不知道您是否已经这样做了,但想避免以后再遇到其他麻烦。
编辑:
假设controller.player.currentIndex是正在播放的单元格的(可选)索引,则看起来像这样:
func configurePlaylistCell (tableView: UITableView, cell: PlaylistCell, controller: AudioController, indexPath: IndexPath){
cell.playPauseButton.tag = indexPath.row + 100
cell.playButtonPressed = { [weak self] (sender: UIButton) in
self?.indexPathForCell = IndexPath(row: sender.tag - 100 , section: 0)
if !controller.audioSessionController.audioSessionIsActive {
try? controller.audioSessionController.activateSession()
}
print (controller.player.currentIndex)
if let item = controller.player.currentItem {
if let index = controller.player.currentIndex, let cell = tableView.cellForRow(at: IndexPath(row: index, section: YOUR_SECTION_FOR_LANGUAGE_CELL)) as! AppSettingViewCell {
cell.playButton.image = UIImage(named: "IMAGE NAME")
}
if (indexPath.row == 0) {
try? controller.player.load(item: item, playWhenReady: true)
}else {
try? controller.player.jumpToItem(atIndex: sender.tag - 100, playWhenReady: true)
}
}
else {
controller.player.togglePlaying()
}
}
}
关于ios - 在Swift中使用Audio Player更改UITableView中按钮单元格的播放暂停状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60014319/