I'm having some trouble implementing a UISwitch in a UITableViewCell. My tableViewCell:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
    let cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")
    cell.textLabel?.text = "Hello Magic Switch buyers!"
    cell.textLabel?.textColor = UIColor.whiteColor()
    cell.backgroundColor = UIColor.clearColor()
    lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
    lightSwitch.on = false
    lightSwitch.addTarget(self, action: "switchTriggered", forControlEvents: .ValueChanged );
    cell.accessoryView = lightSwitch
    return cell
}
This creates the switch, everything goes right, until the point the function gets called.. What you would normally do with for example a button, is just using it's indexPath.row to make a difference between all the cells, but as this is an accessory view, I wasn't able to get this working! The switchTriggered function:
func switchTriggered() {
    if lightSwitch.on {
        let client:UDPClient = UDPClient(addr: "192.168.1.177", port: 8888)
        let (_) = client.send(str: "HIGH" )
        print(String(indexPath.row) + " set to high")
    } else {
        let client:UDPClient = UDPClient(addr: "192.168.1.177", port: 8888)
        let (_) = client.send(str: "LOW" )
        print(String(indexPath.row) + " set to low")
    }
}
The function doesn't know which lightSwitch was switched and what the indexPath is.. How could I fix this? If it was a button, I could use accessoryButtonTappedForRowWithIndexPath but this is not the case.
Some help would be appreciated, as all the information about UISwitches in TableViewCells is in Objective-C.
Thank you very much!
The easiest solution is to use tag property of the switch. When creating switch, assign a tag
lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
lightSwitch.tag = 2000
lightSwitch.addTarget(self, action: Selector("switchTriggered:"), forControlEvents: .ValueChanged );
Then modify your handler method to have a sender parameter
func switchTriggered(sender: AnyObject) {
    let switch = sender as! UISwitch
    if switch.tag == 2000 {
        // It's the lightSwitch
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With