I have a table view with buttons in each of the cell. Each of the button playing different song for each of the cell and change image to "play" or "pause". But I have a problem, when I tap on two or three of buttons, they changes photo to "pause". It should change photo only on one of them. Check photo: Buttons in cell
There is my code in view controller:
extension BeatPackViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 12
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: CustomLoopsCell = beatTableView.dequeueReusableCell(withIdentifier: "firstLoopCell", for: indexPath) as! CustomLoopsCell
gettingSongName()
cell.loopNameLabel.text = data[indexPath.row].loop_name
cell.producerLabel.text = data[indexPath.row].producer
cell.instrumentLabel.text = data[indexPath.row].Instrument
cell.delegate = self
cell.selectionStyle = .none
cell.tag = indexPath.row
if let playingCell = currentPlayingIndex {
if playingCell == indexPath.row {
cell.playButtonOutlet.setImage(UIImage(named: "Pause.png"), for:
.normal)
}
} else {
cell.playButtonOutlet.setImage(UIImage(named: "playBtn.png"), for:
.normal)
}
// cell.instrumentLabel.text = data[indexPath.row].loops[indexPath.row].Instrument
// cell.producerLabel.text = data[indexPath.row].loops[indexPath.row].producer
return cell
}
func btnUseTap(cell: CustomLoopsCell) {
let indexPath = self.beatTableView.indexPath(for: cell)
if currentPlayingIndex == cell.tag {
audioPlayer.pause()
currentPlayingIndex = nil
beatTableView.reloadData()
} else { //IF PAUSE BUTTON
playLoop(song_name: songs[cell.tag])
currentPlayingIndex = cell.tag
beatTableView.reloadData()
}
beatTableView.reloadData()
// playSong(index: indexPath!.row)
print("Done")
}
2
Answers
1)Firstly create empty array of your buttons, for example:
2)When you are creating each cell, add button of that cell to array , Example code:
3)create function that will mute all buttons and also assigning pause image to them, for example:
create function that will handle muting all buttons, and then playing music from selected button, for example:
}
when user clicks on selected cell, call userSelected function. For example:
userSelectedButton(at: yourCellIndex)
Looks like you have problem in your
if
:When
currentPlayingIndex != nil
andplayingCell != indexPath.row
, it doesn’t update the image, so it gets random image from dequeued cell. Change it to:Also you have redundant
reloadData
s here:Just remove both from
if
/else
and left one after theif
/else
.