I have a music list tableView, the data on the cell are from music model. I want to change the color of the 2 labels from the default color white to red when the cell is selected. There is a property named isSelected in the music model which is used to indicates the cell is selected or not.So I use the following code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "MusicTableViewCell", for: indexPath) as! MusicTableViewCell
cell.music = musics[indexPath.row]
cell.numberLabel.text = String(indexPath.row + 1)
if musics[indexPath.row].isSelected == false {
cell.titleLabel.textColor = .white
cell.artistLabel.textColor = .white
cell.speakerImageView.isHidden = true
cell.numberLabel.isHidden = false
} else {
cell.titleLabel.textColor = UIColor(r: 227, g: 0, b: 24)
cell.artistLabel.textColor = UIColor(r: 227, g: 0, b: 24)
cell.speakerImageView.isHidden = false
cell.numberLabel.isHidden = true
musics[indexPath.row].isSelected = true
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if lastSelectedIndexPath != nil {
let cell = tableView.cellForRow(at: lastSelectedIndexPath)! as! MusicTableViewCell
cell.titleLabel.textColor = .white
cell.artistLabel.textColor = .white
cell.speakerImageView.isHidden = true
cell.numberLabel.isHidden = false
musics[lastSelectedIndexPath.row].isSelected = false
}
let cell = tableView.cellForRow(at: indexPath) as! MusicTableViewCell
cell.titleLabel.textColor = UIColor(r: 227, g: 0, b: 24)
cell.artistLabel.textColor = UIColor(r: 227, g: 0, b: 24)
cell.speakerImageView.isHidden = false
cell.numberLabel.isHidden = true
lastSelectedIndexPath = indexPath as IndexPath
currentMusicIndex = indexPath.row
musics[currentMusicIndex].isSelected = true
}
}
I firstly click the 2nd cell and then scroll the tableview to bottom, and click the last cell, but the app will crash.The log is: unexpectedly found nil while unwrapping an Optional value
How to solve it? Thanks.