简体   繁体   中英

Toggle switch on TableViewCell tap

I have two little questions/issues:
1. I want to toggle my switch when I tap my tableViewCell? Is it possible to do without using didSelectRow?
2. Another little issue is when I tap a cell, it's background color stays gray/highlighted. I want it to be gray only in the moment of tapping a cell. Is that possible?

If I understand it correctly, you just want the highlight to disappear right after the tap.

If that's what you want, you can call directly deselectRow in the didSelectRowAt indexPath method:

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

Yes you can, below you find solution for both issues..

1) add button in cellforrow and use add target method. so whenever you click on button it will call your action method. so without using didselect method you can fire your action.

you can use like this...

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) you can use below code :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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