以编程方式突出显示Swift中的UITableViewCell

时间:2018-03-26 20:19:23

标签: ios swift tableview cell

如何以编程方式突出显示表格视图单元格?

我正在使用:

tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
tableView.delegate?.tableView!(self.ordersTableView, didSelectRowAt: indexPath)

我遇到的问题是正在选择单元格(正在执行我didSelectRowAt中指定的所有操作),但单元格现在突出显示。它似乎没有被选中。
我想要实现的就像iPad上的设置应用程序。您启动应用程序并查看已选中并突出显示的“常规”单元格 当用户触摸时,单元格会正确突出显示。

我甚至尝试覆盖我的UITableViewCell子类中的isSelected变量。

好的结果证明这是后台任务的问题。我选择它们后再次加载细胞,这就是选择不可见的原因。

3 个答案:

答案 0 :(得分:0)

试试这个: -

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
var selectedCell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!
selectedCell.contentView.backgroundColor = UIColor.redColor()
}

答案 1 :(得分:0)

注意:您的问题标题显示,您有一个带有单元格突出显示的查询,而您的问题描述说明,您的单元格选择存在问题。两者都是不同的事件。

以下是一个答案,您可以如何管理(设置颜色)tableview行(单元格)选择:

// make sure your tableview row selection is enabled
yourTableViewInstance.allowsSelection = true


// handle highlighted background in data source method also
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "textview") as! YourTableViewCell
    cell.contentView.backgroundColor = cell.isSelected ? UIColor.red : UIColor.gray
    return cell
}



// didSelectRowAtIndexPath - change background color
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell {
        cell.contentView.backgroundColor = UIColor.red
    }
}


// didDeselectRowAtIndexPath - change background color
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell {
        cell.contentView.backgroundColor = UIColor.gray
    }
}

答案 2 :(得分:0)

这是处理单元格背景选择的另一个选项

class YourTableViewCell: UITableViewCell {

    // override cell selection
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

      if self.selectedBackgroundView == nil {
        let bgView = UIView()
        self.selectedBackgroundView = bgView
      }
      self.selectedBackgroundView?.backgroundColor = selected ? UIColor.red : UIColor.gray
    }


}


// enable row/cell selection
yourTableViewInstance.allowsSelection = true


// handle highlighted background in data source method also
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "textview") as! YourTableViewCell

     if self.selectedBackgroundView == nil {
        let bgView = UIView()
        self.selectedBackgroundView = bgView
    }
    self.selectedBackgroundView?.backgroundColor = selected ? UIColor.red : UIColor.gray

    return cell
}
相关问题