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

烈酒焚心 提交于 2019-12-02 21:24:55

When I want events to propagate from a cell to the containing controller, I usually define a custom delegate, like this:

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

use it in the cell:

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

implement the protocol in the view controller and set the delegate in the cell:

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

When the switch is tapped, the event is propagated to the view controller, with the new status and the cell itself passed as arguments. From the cell you can obtain the index path, and then do whatever you need to, such as selecting the row etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!