在Swift中点击其UISwitch时,selectUITableView的行

这个问题已经在Objective-C中find了。 但是我正在Swift工作,也有类似的问题。

一旦成功创build,当我点击它的UISwitch时,如何selectUITableView的行?

我在我的模型中有一个布尔值,并希望根据开关的开/关状态来切换布尔值。

我有一些编程创build的单元格包含开关…

视图控制器:

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

当轻击开关时,事件传播到视图控制器,新的状态和单元本身作为parameter passing。 从单元格中可以获得索引path,然后执行所需的任何操作,例如select行等。