【发布时间】:2017-05-31 14:48:40
【问题描述】:
我最近发现我的代码有一个错误,在尽我所能解决它之后,我能够弄清楚我认为正在发生的事情。在我的应用程序中,如果用户选择该单元格,我会更改背景颜色,这样您就可以选择多个单元格。但是,如果选择了第一个单元格,它将取消选择(更改背景颜色)所有其他单元格。但事实证明我收到以下错误:
致命错误:在展开可选值时意外发现 nil
当我尝试更改屏幕上不可见的单元格的背景颜色时。我假设这是因为只有可见单元格被加载到内存中,而所有其他单元格只有在它们再次可见时才会被加载。
那么我将如何手动加载一个我知道 IndexPath 但也知道它在视图之外的单元格。另外,有没有办法知道 IndexPath 处的单元格是否已加载?
这是我当前的代码。
func selectAnyList(tableView: UITableView) {
let sections = frc!.sections!
let currentSection = sections[0]
let numRows = currentSection.numberOfObjects
for i in 0...(numRows - 1) {
let indexPath = IndexPath(row: i, section: 0)
let cell = tableView.cellForRow(at: indexPath) as! ItemListTVCell //This is where the error happens if the cell is not visible
if (i == 0) {
cell.backgroundColor = UIColor.activeAqua.withAlphaComponent(0.85)
} else {
cell.backgroundColor = UIColor.white.withAlphaComponent(0.85)
}
}
}
编辑:添加单元格的加载方式
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let list: Ent_Lists = frc!.object(at: indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: "itemListCell", for: indexPath) as! ItemListTVCell
if (list == Ent_Lists.anyList) {
self.anyCell = cell
}
cell.listName.text = list.name
cell.listImage.image = list.image!.uiImage
if ((indexPath as NSIndexPath).row != 0 && listSet!.contains(list)) {
numLists += 1
}
return cell
}
【问题讨论】:
-
您的列表中是否有一些模型的数组?如果是,请添加一个名为 bgColor 的额外属性,并对其进行更新。
-
我还是个很绿色的程序员,我不确定我是否理解你的建议。
-
你能展示一下
Ent_Lists的样子吗? -
添加了来自 Coredata 的
Ent_Lists的图像 -
您是否总是希望第一个单元格的背景颜色不同?或者它可以是任何单元格,其 bg 颜色应该与其他单元格不同?
标签: uitableview swift3 ios10 tableviewcell xcode8