ios - 关闭作为 UITableViewCell 子类的属性以更新值 : Is it a bad idea?

标签 ios swift uitableview closures

<分区>

我想对我刚刚的想法提出一些意见:

我有一堆 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)
    }
}


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

...
} 

作为优点,我看到以下内容:

  • 无需委托(delegate)
  • 在我需要确定需要更新哪个值的地方没有调用任何方法(我的单元格有多个实例用于不同的变量)

我无法理解我的想法可能存在的缺点,以及它总体上是好还是坏的想法。

最佳答案

就我个人而言,我有点守旧,只是更喜欢委托(delegate)模式而不是闭包。

但是对于你的问题……你的建议正是闭包的用途。去吧。

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

关于ios - 关闭作为 UITableViewCell 子类的属性以更新值 : Is it a bad idea?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33809249/

相关文章:

swift - 在 iOS 上使用 Core Image 二值化图片

ios - mask 后如何去除 UIImageView 的透明区域?

ios - Swift - 简单 if 语句中的意外错误

macos - addSubview(...) 导致额外的窗口

ios - 使用静态按钮检查值并显示在屏幕上

iOS tableview 如何检查它是向上还是向下滚动

iphone - 将重新排序控件移至左侧

iphone - 是否可以在 UITableView 上使用其他 UIControl?

objective-c - 使用 iOS 版 Facebook 登录

ios - CloudKit 的单元测试