0

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?

faris97
  • 402
  • 4
  • 24
  • 1
    You can add a transparent button and toggle switch when that button is tapped. But its easier to use `didSelectRow` – iOSDev Feb 05 '20 at 12:43
  • 1
    If you don't want to use didSelectRow...you can register a tap gesture and work with that...if you need code for that please let me know. – Mohit Kumar Feb 05 '20 at 12:44
  • 1
    Use `didSelectRow` only for 2) to deselect the row. For 1) use a callback closure in `cellForRow`. – vadian Feb 05 '20 at 13:04
  • @vadian How about answering? Your suggestions sound good. – faris97 Feb 05 '20 at 13:06
  • Please see https://stackoverflow.com/questions/43409799/how-to-get-rowindex-by-switchbutton-of-tablecellview-custom/43409998#43409998 – vadian Feb 05 '20 at 13:07

2 Answers2

1

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
    }
Enricoza
  • 1,101
  • 6
  • 18
1

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