【问题标题】:Swift - Change background color in tableView.selectRowSwift - 在 tableView.selectRow 中更改背景颜色
【发布时间】:2020-03-16 19:51:34
【问题描述】:

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

【问题讨论】:

  • 细胞被重复使用。在cellForRowAt 之外操作单元格是非常危险的,除非你知道自己在做什么????。
  • @vadian 谢谢,但这对我解决这个特殊问题没有帮助。
  • @paco8 简单:不要操作单元格,而是使行无效。

标签: ios swift uitableview


【解决方案1】:

UITableViewCell 的选择颜色是单元格子视图的背景颜色。

你可以试试这个:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

/// dequeueReusableCellWithIdentifier...
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.green
cell.selectedBackgroundView = backgroundColorView
}

【讨论】:

  • 太棒了!谢谢!你让我的隔离更快乐:-)
猜你喜欢
  • 2020-08-29
  • 1970-01-01
  • 2015-11-18
  • 2018-10-25
  • 2020-01-26
  • 2018-01-01
  • 2017-02-09
  • 2015-10-09
  • 2013-08-08
相关资源
最近更新 更多