Select 在 Swift 中点击其 UISwitch 时 UITableView 的行

Select UITableView's row when tapping on its UISwitch in Swift

此问题已在 Objective-C 中被解决 here。但我在 Swift 工作,也有类似的问题。

创建成功后,如何在点击 UISwitch 时 select UITableView 的行?

我的模型中有一个布尔值,我想根据开关 on/off 状态切换该布尔值。

我有一些以编程方式创建的包含开关的单元格...

视图控制器:

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
    }

基于 SettingItem.swift 中的模型:

class SettingItem: NSObject {

    var settingName : String?
    var switchState : Bool?

    init (settingName: String?, switchState : Bool?) {
        super.init()
        self.settingName = settingName
        self.switchState = switchState
    } 
}

我在SettingCell.swift有一些分店:

class SettingCell: UITableViewCell {

    @IBOutlet weak var settingsLabel: UILabel!

    @IBOutlet weak var settingsSwitch: UISwitch!


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

产生这个(请忽略格式):

当我希望事件从单元传播到包含控制器时,我通常会定义一个自定义委托,如下所示:

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)
        ...
    }
}

点击开关时,事件将传播到视图控制器,新状态和单元格本身作为参数传递。从单元格中可以获得索引路径,然后做任何你需要做的事情,比如选择行等