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 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()
Radio Stations are changing without problem, having issue only with play/pause icon state
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:
In your delegate:
UPDATE: I have updated my answer to store the playback state in item.
Use the MVC pattern instead of storing data in the view object or the global(view controller) scope. Then your life will be much easier.
I think each row should be backed by a model object. Say:
then your
cellForRowAtIndexPath
method:then in your
didSelectRowAtIndexPath
method, change the selected itemisPlaying = true
and all the other itemsisPlaying = false
, and calltableView.reloadData()
. The table view will refresh all the cells to reflect their correct state.