关闭作为UITableViewCell子类的属性来更新值:这是一个坏主意吗?

Mat*_*ler 6 closures uitableview ios swift

我想对我刚才的想法提出一些看法:

我有一堆UITableViewCell子类.在我的特定情况下,它只是添加一个UISwitch并具有访问它的属性.

设置开关的值是直截了当的.更新与此开关关联的Bool并非如此.

我想添加一个闭包作为我的单元格的属性,以便我可以调用它来更新我的UITableViewController子类中的bool

这是我想到的一些代码:

class SwitchTableViewCell:UITableViewCell {
    @IBOutlet var theSwitch:UISwitch!

    var switchValueChangedBlock:((Bool) -> Void)?

    override func awakeFromNib() {
        theSwitch.addTarget(self, action: "switchValueChanged", forControlEvents: .ValueChanged)
    }

    deinit {
        theSwitch.removeTarget(self, action: nil, forControlEvents: .AllEvents)
    }

    func setCallback(callback:(Bool) -> Void) {
        switchValueChangedBlock = callback
    }

    func switchValueChanged() {
        switchValueChangedBlock?(theSwitch.on)
    }
}
Run Code Online (Sandbox Code Playgroud)


class myTableViewController:UITableViewController {
    var alarmEnabled:Bool = true
 ...
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell:UITableViewCell?
        if indexPath.section == enableSection {
            cell = tableView.dequeueReusableCellWithIdentifier(enableAlarmCellIdentifier,forIndexPath: indexPath)
            let myCell = cell as! SwitchTableViewCell
            myCell.theSwitch.on = alarmEnabled
            myCell.setCallback({[unowned self] (boolValue:Bool) in
                self.alarmEnabled = boolValue
            })
        }
    }

...
} 
Run Code Online (Sandbox Code Playgroud)

我看到以下优点:

  • 不需要代表
  • 没有方法调用我需要确定哪个值需要更新(我的单元格的多个实例用于不同的变量)

我无法理解我的想法可能存在的缺点,如果总的来说这是一个坏或好主意.

Her*_*ker 3

就我个人而言,我有点老派,只是更喜欢委托模式而不是关闭。

但对于你的问题......你的建议正是闭包的目的。就去做吧。

您只需将想要在某些事件发生时执行的一段代码(或分别对某个子例程的入口点的引用)移交给另一个类的对象即可。这就是它的用途,这就是您正在做的事情。