This question has been approached here in Objective-C. But I am working in Swift and have a similar question.
Once successfully created, how do I select the UITableView's row when I tap on its UISwitch?
I have a boolean in my model and would like to toggle that boolean based on the switches on/off state.
I have some programmatically created cells that contain switches...
View Controller:
var settings : [SettingItem] = [
SettingItem(settingName: "Setting 1", switchState: true),
SettingItem(settingName: "Setting 2", switchState: true)
]
override public func tableView(_tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomSettingCell") as! SettingCell
let settingItem = settings[indexPath.row]
cell.settingsLabel.text = settingItem.settingName
cell.settingsSwitch.enabled = settingItem.switchState!
return cell
}
based off a model in SettingItem.swift:
class SettingItem: NSObject {
var settingName : String?
var switchState : Bool?
init (settingName: String?, switchState : Bool?) {
super.init()
self.settingName = settingName
self.switchState = switchState
}
}
and I have some outlets in SettingCell.swift:
class SettingCell: UITableViewCell {
@IBOutlet weak var settingsLabel: UILabel!
@IBOutlet weak var settingsSwitch: UISwitch!
@IBAction func handledSwitchChange(sender: UISwitch) {
println("switched")
}
Which produces this (please ignore the formatting):