在Objective-C中已向here处理了这个问题。但是我在Swift公司工作,有一个类似的问题。

一旦成功创建,当我点击UITableView的UISwitch时如何选择它?

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

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

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
    }

基于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")
    }

生成此代码(请忽略格式):

最佳答案

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

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

在 View Controller 中实现协议(protocol),并在单元格中设置委托(delegate):
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)
        ...
    }
}

轻按开关时,事件将传播到 View Controller ,并以新状态和单元格本身作为参数传递。您可以从单元格中获取索引路径,然后执行所需的任何操作,例如选择行等。

关于ios - 在Swift中点击其UISwitch时,选择UITableView的行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29516730/

10-14 16:59
查看更多