Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

identifying a UISwitch in UITableViewCell

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!

like image 921
Bram Roelandts Avatar asked Mar 04 '16 21:03

Bram Roelandts


1 Answers

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
    }
}
like image 149
Rafa de King Avatar answered Nov 19 '22 05:11

Rafa de King