![](/img/trans.png)
[英]When to call tableView.selectRow to avoid UITableViewAlertForCellForRowAtIndexPathAccessDuringUpdate
[英]Swift - Change background color in tableView.selectRow
我有一个具有所有正确行为的 tableView,但我试图将选定行的背景颜色从默认的灰色更改为绿色,并且 tableView 表现得很奇怪。
默认颜色的当前行为:页面加载并且第一个表格部分的第一行被选择为默认值(灰色背景)。 如果用户单击另一行,则取消选择第一行,单击的将获得灰色背景。 这段代码:
private var scrolledToItitialSelection = false
didSet {
tableView.reloadData()
if let selected = self.model.selectedRow { // selectedRow returns an indexPath
tableView.selectRow(at: selected, animated: true, scrollPosition: scrolledToInitialSelection ? .none : .middle
scrolledToItitialSelection = true
}
}
我试图实现完全相同的行为,只是使用不同的背景颜色。 但是在下面的代码中,tableView 加载并按预期选择了第一个表格部分的第一行,但第二部分的第二行也是如此。 另外,如果我单击默认选择的行下方的行,现在我有 4 个选定的行:第一部分中有两个,第二部分中有两个。
private var scrolledToItitialSelection = false
didSet {
tableView.reloadData()
if let selected = self.model.selectedRow { // selectedRow returns an indexPath
tableView.selectRow(at: selected, animated: true, scrollPosition: scrolledToInitialSelection ? .none : .middle
let selectedCell:UITableViewCell = tableView.cellForRow(at: selected)!
selectedCell.contentView.backgroundColor = .green
selectedCell.accessoryView.backgroundColor = .green
scrolledToItitialSelection = true
}
}
UITableViewCell
选择颜色是单元格子视图的背景颜色。
你可以试试这个:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
/// dequeueReusableCellWithIdentifier...
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.green
cell.selectedBackgroundView = backgroundColorView
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.