0

I want to use subtitle style of table view cell (not the custom one), and also I need to have an UISwitch in the right side of the cell. if the name of the cell is TitleCell I know I can add a UISwitch programmatically to it by using this line of code:

TitleCell.accessoryView = UISwitch()

But can I have access to this UISwitch and using it as an outlet and giving it an action?

Thanks for your help in advance

battlmonstr
  • 5,841
  • 1
  • 23
  • 33
JOnney
  • 89
  • 1
  • 8

2 Answers2

0

You can give an action to the switch programmatically by calling addTarget (see UISwitch: Swift 3: Programmatically ).

Also consider moving to a custom cell xib/class. It is not hard to set up, but then you have full control over what is there and how it is laid out.

battlmonstr
  • 5,841
  • 1
  • 23
  • 33
  • thanks for your help. I usually use custom style, but as Im working on the setting page and all cells must have icon, subtitle style with an image is quite prefect for my work and I don't need worry about the size of the image and constraints. I looked at the website that you post it, but they use normal add to subview, but the adding with method that I use, doesn't give me any thing to access to the UIswitch inside it, at least I don't know how – JOnney Mar 31 '19 at 18:38
  • Are you saying that it doesn't work if you addTarget when you have an accessoryView ? – battlmonstr Mar 31 '19 at 18:45
  • Also note that if you do addTarget , you get your UISwitch as the "sender" parameter to your selector. You can assign a tag inside UISwitch (`mySwitch.tag = rowIndex`), and be able to find the cell by index with that from the action callback. – battlmonstr Mar 31 '19 at 18:47
0

After assigning the switch to the accessory view you can access it with

if let mySwitch = TitleCell.accessoryView as? UISwitch {
   // it's the switch, you can use it.
}

However you are encouraged to design a custom cell with an outlet by subclassing UITableViewCell

And please conform to the naming convention that variable names start with a lowercase letter.

vadian
  • 274,689
  • 30
  • 353
  • 361