如何解决在数组的单元格中显示图像
我有 TableViewController
和 AudioPlayerViewController
。在 TableViewController
中,我想知道已收听了多少首曲目。并在监听的单元格 TableViewController
中显示图像。为了检测该曲目是否已被收听,我在 AudioPlayerViewController
中使用了此代码:
func audioPlayerDidFinishPlaying(_ audioPlayer: AVAudioPlayer,successfully flag: Bool) {
UserDefaults.standard.set( arrayOfListened(trackIndex),forKey: "key")
}
然后在 TableViewController
中的监听单元格中显示图像:
override func tableView(_ tableView: UITableView,cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(format: "cell",indexPath.row),for: indexPath) as! MasterViewCell
if indexPath.row == arrayOfListened[indexPath.row] {
cell.cellStatusImage.image = UIImage(named: "statusDone.png")
}
}
但是我的应用程序崩溃了。如何解决?
解决方法
问题是您试图通过 indexPath.row
从数组中获取一个可能不存在的元素。尝试使用这样的东西:
...
guard
arrayOfListened.indices.contains(indexPath.row),indexPath.row == arrayOfListened[indexPath.row]
else {
return cell
}
... your cell configuration
或者,如果您的 arrayOfListened 只包含歌曲 ID,您可以简单地使用:
if arrayOfListened.contains(indexPath.row) {
... your cell configuration
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。