Select UITableView row when clicking on UISwitch in Swift

This question was addressed here in Objective-C. But I work in Swift and have a similar question.

After successfully creating, how to select the UITableView row when I click on my UISwitch?

I have a boolean in my model and would like to switch this boolean based on the on / off state.

I have programmatically created cells containing keys ...

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 on the model in SetItem.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 points in SetCell.swift:

class SettingCell: UITableViewCell {

    @IBOutlet weak var settingsLabel: UILabel!

    @IBOutlet weak var settingsSwitch: UISwitch!


    @IBAction func handledSwitchChange(sender: UISwitch) {
        println("switched")
    }

What produces this (please ignore formatting):

enter image description here

+4
source share
1

, , , :

protocol SettingCellDelegate : class {
    func didChangeSwitchState(# sender: SettingCell, isOn: Bool)
}

:

class SettingCell: UITableViewCell {
    @IBOutlet weak var settingsLabel: UILabel!
    @IBOutlet weak var settingsSwitch: UISwitch!

    weak var cellDelegate: SettingCellDelegate?

    @IBAction func handledSwitchChange(sender: UISwitch) {
        self.cellDelegate?.didChangeSwitchState(sender: self, isOn:settingsSwitch.on)
        ^^^^
    }
}

:

class ViewController : UITableViewController, SettingCellDelegate {
                                              ^^^^
    override 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!

        cell.cellDelegate = self
        ^^^^

        return cell
    }

#pragma mark - SettingCellDelegate

    func didChangeSwitchState(#sender: SettingCell, isOn: Bool) {
        let indexPath = self.tableView.indexPathForCell(sender)
        ...
    }
}

, . , , , , ..

+19

All Articles