Raja Rupinder Singh Raja Rupinder Singh - 3 months ago 32
iOS Question

How to save changed state of dynamic created UISwitch in CoreData model in Swift?

I have a

UITableView
containing dynamic cells added by user. Each cell has one
UILabel
and one
UISwitch
. The default state of switch is ON. I save these values in a
CoreData
model (
UILabel
as String &
UISwitch
as
Bool
) whenever user adds it.
I would like to update/store the state of switch corresponding to value of label in the same cell in CoreData model whenever user toggles the switch. I have added tags (switch.tag = indexPath.row) to each switch in row and can access it by using sender.tag in my cellChanged function. But I am not able to fetch label of that row in which switch has been toggled. If I can somehow fetch value of label corresponding to the switch toggled then I can run a for loop to look for that label value in
CoreData
model and then subsequently set state of
UISwitch
. Since I am using
Swift
language, I will appreciate if you can explain code using the same.

Answer

This worked for me:

func switchTapped(sender:UISwitch) {
let switchPosition = sender.convertPoint(CGPointZero, toView: self.tableView)
let indexPath = self.tableView.indexPathForRowAtPoint(switchPosition)

}