swift - UITableViewCell 设置 contentView backgroundColor 多于一个section
问题描述
在 UITableView 的 didSelectRow 方法中,我正在更改 UITableViewCell 的 contentView.backgroundColor ,但我有 2 个部分,当我使用以下内容投射单元格时:
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath)!
并设置selectedCell.contentView.backgroundColor
代码更改两个部分的背景颜色。如何仅从 中投射单元格indexPath.section
?
更新来自@rmaddy 的回答
当我在 didSelectRow 方法中保存变量 indexPath.row 和 indexPath.section 并使用 willDisplay 单元格或 cellForRow 中的变量来设置 backgroundColor 时,它会在每 8-16-32-64 行上自动设置 backgroundColor。
更新 2:在 cellForRow 我设置这个:
if(indexPath.row == selectedFromIndex && indexPath.section == selectedFromSection){
cell.contentView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.1)
}else{
cell.backgroundColor = .clear
cell.isSelected = false
}
selectedFromIndex 和 selectedFromSection 是保存在 didSelectRowMethod 中的变量。选择仍然出现在第 8-16-32-64 行...
解决方案
这与铸造无关。您只需要一份if
声明来检查该部分。
if indexPath.section == 0 { // 1 depending on which section you need
// get the cell and set the background color
}
但这会随着用户滚动而失败。您应该做的didSelectRow
是更新您的数据模型以跟踪已选择哪些行以及哪些行应该获得不同的颜色背景,然后告诉表视图重新加载该行。
然后cellForRowAt
(或willDisplay:forRowAt:
)中的代码应使用该数据根据需要设置单元格的颜色。
无论您使用哪种方法,请确保根据需要设置或重置背景颜色,因为行被重用:
// pseudo code:
if row is selected {
cell.backgroundColor = .someSelectedColor
} else {
cell.backgroundColor = .someUnselectedColor
}
推荐阅读
- javascript - JavaScript 将 CSS 应用于图像并保存
- python - 在 model.fit() 中使用图像生成器作为 y 参数
- latex - 即使缺少某些变量,如何对齐数学方程?
- html - 如何使按钮居中
- flutter - 在颤动中更改页面时保持小部件始终可见
- wordpress - 如何在 Godaddy 的 2 个不同托管站点托管主域和子域?
- ruby - 类方法中的变量
- azure-devops - 需要从 azure 管道中的变量设置条件
- angular - 如何防止剑道抽屉在点击时折叠?(角度 - 剑道用户界面)
- linux - docker-entrypoint exec nginx 未找到