UITableViewCell在DidSelectRow

时间:2019-06-22 15:35:28

标签: swift

我要在选择表格时更改背景。现在,当我选择两个表时,背景更改为2。我只想更改最后选择的表的背景。因此,只需更改一个表的背景,而不是两个。更改我选择的最后一幅画的背景。

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     if tableView == self.tableView1 {
        let cell:DeviceTableViewCell2 = tableView1.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! DeviceTableViewCell2
  cell.selectionStyle = .none

            cell.backgroundColor = GradientColor(UIGradientStyle.diagonal, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])

        }
        if tableView == self.tableView2 {
            let cell:DeviceTableViewCell2 = tableView2.dequeueReusableCell(withIdentifier: cellIdNew, for: indexPath) as! DeviceTableViewCell2
 cell.selectionStyle = .none

                cell.backgroundColor = GradientColor(UIGradientStyle.diagonal, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])

            }
  if tableView == self.tableView3 {
                let cell:DeviceTableViewCell2 = tableView3.dequeueReusableCell(withIdentifier: cellIdNew2, for: indexPath) as! DeviceTableViewCell2
cell.selectionStyle = .none


                cell.backgroundColor = GradientColor(UIGradientStyle.diagonal, frame: self.view.frame, colors: [UIColor.flatPowderBlueDark, UIColor.flatSand])
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if tableView == self.tableView1 {
let selectedCell:UITableViewCell = tableView1.cellForRow(at: indexPath)!
                    selectedCell.contentView.backgroundColor = UIColor.flatGray
}
 if tableView == self.tableView2 {
 let selectedCell2:UITableViewCell = tableView2.cellForRow(at: indexPath)!
                        selectedCell2.contentView.backgroundColor = UIColor.flatGray
                    }
if tableView == self.tableView3 {
 let selectedCell3:UITableViewCell = tableView3.cellForRow(at: indexPath)!
                        selectedCell3.contentView.backgroundColor = UIColor.flatGray
}

1 个答案:

答案 0 :(得分:1)

请勿更改contentView或单元格本身的selectedBackgroundView,而应使用 cell.backgroundView = UIView() cell.backgroundView?.backgroundColor = // your color when not selected cell.selectedBackgroundView = UIView() cell.selectedBackgroundView?.backgroundColor = // your color when selected

cell.selectionStyle = .none

此初始设置后,无需更改任何内容。一切都会自动运行。

请勿设置<option>,因为这将完全禁用选择。

相关问题