Reputation: 85
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
}
Upvotes: 5
Views: 8963
Reputation: 23459
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.
Upvotes: 7
Reputation: 2049
Eric,
At some point in the tableview's lifecycle, you'll need to configure each UISwitch in the table cell with a target/action.
The action
tells the UISwitch instance what method it should invoke when the switch is flipped by the user. The target
tells the UISwitch instance what object is hosting that method.
Typically, you'll use the UITableViewController (or UIViewController) subclass as the target.
Upvotes: 0
Reputation: 12697
You need to listen .ValueChanged of UISwitch, in YOUR_CUSTOM_CELL to make some decisions. There you can catch to "println" your data.
Upvotes: 0