在 TableViewCell tap 上切换开关

Toggle switch on TableViewCell tap

我有两个小questions/issues:
1. 我想在点击 tableViewCell 时切换开关?不使用 didSelectRow 可以吗?
2. 另一个小问题是当我点击一个单元格时,它的背景颜色保持 gray/highlighted。我希望它仅在点击单元格时才显示为灰色。这可能吗?

如果我没理解错的话,你只是希望突出显示在点​​击后立即消失。

如果这是你想要的,你可以在didSelectRowAt indexPath方法中直接调用deselectRow:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        // Do your custom logic / toggle your switch
    }

是的,您可以在下面找到解决这两个问题的方法..

1) 在cellforrow中添加按钮,使用add target方法。因此,无论何时单击按钮,它都会调用您的操作方法。所以不使用 didselect 方法你可以触发你的动作。

你可以这样使用...

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
     //add button here programatically or in your storyboard tableviewcell 

      cell.btnTemp.tag = indexPath.section
      cell.btnSelect.addTarget(self, action: #selector(CallyourDesireButtonAction(_:)), for: .touchUpInside)

}

 @objc @IBAction func btnSelectBillingAddressClicked(_ sender: UIButton)
{
   //Perform your action for switch
}

2) 你可以使用下面的代码:

  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) 
    {
          if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell 
          {

             cell.contentView.backgroundColor = UIColor.red
          }
    }



func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) 
 {

     if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell 
    {
          cell.contentView.backgroundColor = UIColor.white
    }
 }