问题描述
所以我有动态的tableview,每一行都有播放图像.如果我选择该行图像将更改为暂停图标.但是,如果我选择另一行,我需要先前选择的行上的图像再次具有播放图标.如何处理这种功能?
So I have dynamic tableview and each row have play image. If I select the row image will change to pause icon. But what if I select another row, I need the image on previously selected row to have play icon again.How to handle such functionality?
我所拥有的是:
class ViewController: UIViewController {
var stations = [
(stationIcon: "rr_icon", stationName: "Radio1", urlString: "http://.._320", isPlaying: false),
(stationIcon: "mm_icon", stationName: "Record2", urlString: "http://../_320", isPlaying: false),
........]
func playSelectedStation(indexPath: NSIndexPath) {
let url = NSURL(string: stations[indexPath.row].urlString)!
stations[indexPath.row].isPlaying = true
avPlayer = AVPlayer(URL: url)
avPlayer.play()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! RadioTableViewCell
cell.playPause.image = stations[indexPath.row].isPlaying ? UIImage(named: "cellPause") : UIImage(named: "cellPlay")
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row {
playSelectedStation(indexPath)
tableView.reloadData()
广播电台正在毫无问题的变化,仅在播放/暂停图标状态方面存在问题
推荐答案
您可以通过浏览可见的单元格并在所有单元格中禁用播放按钮来实现此功能,除了用户刚刚点击的那个按钮:
You can achieve it by going through visible cells and disable play button in all of them except the one the user has just tapped on:
class PlayItem {
// your code
var isPlaying = false
}
class RadioTableViewCell: UITableViewCell {
// your code ....
func setup(item item: PlayItem) {
image = item.isPlaying ? UIImage(named: "cellPause") : UIImage(named: "cellPlay")
}
}
在您的代表中:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.cellForRowAtIndexPath(indexPath) as! RadioTableViewCell
let item = items[indexPath.row] // you may think of storing this array in some kind of view model
cell.setup(item: item)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as! RadioTableViewCell
let selectedItem = items[indexPath.row]
selectedItem.isPlaying = !selectedItem.isPlaying
for cell in tableView.visibleCells {
guard let visibleCell = cell as? RadioTableViewCell else { return }
let path = tableView.indexPathForCell(visibleCell)
let item = items[path.row]
item.isPlaying = visibleCell == selectedCell
visibleCell.setup(item: item)
}
}
更新:我已经更新了答案,将播放状态存储在项目中.
UPDATE: I have updated my answer to store the playback state in item.
这篇关于如果在TableView didSelectRowAtIndexPath函数中选择了其他行,如何将图像更改为以前的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!