Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UISwitch in TableView in Switch

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
}
like image 357
Eric Consford Avatar asked Mar 30 '15 19:03

Eric Consford


People also ask

Is it possible to add UITableView within a UITableViewCell?

yes it is possible, I added the UITableVIew within the UITableView cell .. :) no need to add tableview cell in xib file - just subclass the UITableviewCell and use the code below, a cell will be created programatically.

What does Tableview Register do?

Returns a reusable table-view cell object for the specified reuse identifier and adds it to the table.

What is Indexpath in Tableview Swift?

Swift version: 5.6. Index paths describe an item's position inside a table view or collection view, storing both its section and its position inside that section.


1 Answers

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.

like image 188
Victor Sigler Avatar answered Sep 19 '22 14:09

Victor Sigler