UISwitch in TableView in Switch

Eric Consford picture Eric Consford · Mar 30, 2015 · Viewed 8.4k times · Source

Hello fellow programmers! I have a challenge I need help with. I have built a table using a Custom Style Cell.

This cell simply has a Label and UISwitch. The label displays a name and the switch displays whether they are an Admin or not. This works perfectly. My challenge is how and where do I put code to react when the switch is changed.

So if I click the switch to change it from off to on where can I get it to print the persons name? If I can get the name to print I can do the php/sql code myself. Thanks and here is a snippet from my code.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: UITableViewCell = tableView.dequeueReusableCellWithIdentifier(kCellIdentifier) as UITableViewCell
    let admin = self.admin[indexPath.row]

    let text1a = admin.FirstName
    let text1aa = " "

    let text1b = admin.LastName
    let text1 = text1a + text1aa + text1b
    (cell.contentView.viewWithTag(1) as UILabel).text = text1

    if admin.admin == "yes" {
        (cell.contentView.viewWithTag(2) as UISwitch).setOn(true, animated:true)

    } else if admin.admin == "no" {
        (cell.contentView.viewWithTag(2) as UISwitch).setOn(false, animated:true)
    }

    return cell
}

Answer

Victor Sigler picture Victor Sigler · Mar 30, 2015

You have to set an action in your Custom Table View Cell to handle the change in your UISwitch and react to changes in it, see the following code :

class CustomTableViewCell: UITableViewCell {

     @IBOutlet weak var label: UILabel!

     @IBAction func statusChanged(sender: UISwitch) {
         self.label.text = sender.on ? "On" : "Off"
     }
}

The above example is just used to change the text of the UILabel regarding the state of the UISwitch, you have to change it in base your requirements of course. I hope this help you.