Ray King Ray King - 1 year ago 124
Swift Question

How to change image to previous state if other row is selected in TableView didSelectRowAtIndexPath function?

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?

All I have is

class ViewController: UIViewController {
var isPlaying = false

func playRadioStation() {
if !isPlaying {
isPlaying = true
//image.image = UIImage(named: "cellPause")
else {
isPlaying = false
// image.image = UIImage(named: "cellPlay")
func playSelectedStation(indexPath: NSIndexPath) {
let url = NSURL(string: stations[indexPath.row].urlString)!
avPlayer = AVPlayer(URL: url)

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as! RadioTableViewCell
cell.playPause.image = isPlaying ? UIImage(named: "cellPause") : UIImage(named: "cellPlay")
return cell

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

switch indexPath.row {
case 0:
playRadioStation(indexPath, image: cell.playPause)
case 1:
playRadioStation(indexPath, image: cell.playPause)
print("nothing here")

Radio Stations are changing without problem, having issue only with play/pause icon state

Answer Source

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 RadioTableViewCell {

    // your code ....

    func setup(playbackEnabled playbackEnabled: Bool) {
        image = playbackEnabled ? UIImage(named: "cellPause") : UIImage(named: "cellPlay")
        // additional setup here

And then in your tableview delegate:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let selectedCell = tableView.cellForRowAtIndexPath(indexPath) as! RadioTableViewCell

    for cell in tableView.visibleCells {
        let visibleCell = cell as? RadioTableViewCell
        visibleCell.setup(playbackEnabled: visibleCell == selectedCell)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download