Ios Swift-更改tableView中的背景色。选择行

Ios Swift-更改tableView中的背景色。选择行,ios,swift,uitableview,Ios,Swift,Uitableview,我有一个具有所有正确行为的tableView,但我正在尝试将选定行的背景颜色从默认的灰色更改为绿色,并且tableView的行为很奇怪 默认颜色的当前行为:加载页面,并选择第一个表节的第一行作为默认值(灰色背景)。如果用户单击另一行,第一行将被取消选择,单击的一行将获得灰色背景。此代码: private var scrolledToItitialSelection = false didSet { tableView.reloadData() if let selected =

我有一个具有所有正确行为的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
}

细胞被重复使用。在
cellForRowAt
之外操作单元格是非常危险的,除非您知道自己在做什么@vadian谢谢,但这并不能帮助我解决这个特殊问题。@paco8简单:不要操作单元格,而是使行无效。太棒了!非常感谢。你让我更开心了:-)