UISwitch Authentication in a UITableViewCell

I'm having trouble embedding 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 a switch, everything goes right until the point is called up. What you usually do, for example, using a button, just uses this indexPath.row to make the difference between all the cells, but as an accessory, I could not get this to work! 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 does not know which lightSwitch switch was turned on and what indexPath is. How can I fix this? If it were a button, I could use it accessoryButtonTappedForRowWithIndexPath, but that is not the case.

Some help would be appreciated, since all the UISwitches information in TableViewCells is in Objective-C.

Many thanks!

+4
1

- tag .

lightSwitch = UISwitch(frame: CGRectZero) as UISwitch
lightSwitch.tag = 2000
lightSwitch.addTarget(self, action: Selector("switchTriggered:"), forControlEvents: .ValueChanged );

,

func switchTriggered(sender: AnyObject) {

    let switch = sender as! UISwitch
    if switch.tag == 2000 {
        // It the lightSwitch
    }
}
+6

All Articles