简体   繁体   English

Swift - 在 tableView.selectRow 中更改背景颜色

[英]Swift - Change background color in tableView.selectRow

I have a tableView that has all the correct behaviors, but I am trying to change the background color of a selected row from the default grey to green and the tableView is acting strange.我有一个具有所有正确行为的 tableView,但我试图将选定行的背景颜色从默认的灰色更改为绿色,并且 tableView 表现得很奇怪。

Current behavior with default color: page loads and the first row of the first table section is selected as default (grey background).默认颜色的当前行为:页面加载并且第一个表格部分的第一行被选择为默认值(灰色背景)。 If user clicks another row, the first one is deselected and the one clicked gets the grey background.如果用户单击另一行,则取消选择第一行,单击的将获得灰色背景。 This code:这段代码:

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
    }
}

I am trying to achieve the exact same behavior, only with a different background color.我试图实现完全相同的行为,只是使用不同的背景颜色。 But with the code bellow, the tableView loads and the first row of the first table section is selected as expected, but so is the second row of the second section.但是在下面的代码中,tableView 加载并按预期选择了第一个表格部分的第一行,但第二部分的第二行也是如此。 Also, if I click the row bellow the one selected by default, now I have 4 selected rows: two in the first section, two in the second.另外,如果我单击默认选择的行下方的行,现在我有 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
    }
}

Selection color of a UITableViewCell is background color on a subview of the cell. UITableViewCell选择颜色是单元格子视图的背景颜色。

You can try with this:你可以试试这个:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM