ios - 当其中一个属性发生变化时,监听数据模型数组中的更新

标签 ios swift didset property-observer

我有一个自定义的 UITableViewCell,它有一个数据模型数组和一个 UILabel,如下所示:

class ItemCustomizationCollectionViewCell: UITableViewCell {

    var customizationData: CustomizationData?

    let priceLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.boldSystemFont(ofSize: 18)
        label.textAlignment = .left
        label.textColor = UIColor.gray
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }() 

    //other init and constraints
}

现在,CustomizationData 看起来像这样:

class CustomizationData {
    let title: String
    var customizationOptions: [PickerOption]
    var choosenOption: PickerOption?

    init(title: String, customizationOptions: [PickerOption], choosenOption: PickerOption?) {
        self.title = title
        self.customizationOptions = customizationOptions
        self.choosenOption = choosenOption
    }
}

PickerOption 是:

class PickerOption {
    let title: String
    let price: String

    init(title: String, price: String) {
        self.title = title
        self.price = price
    }
}

我的问题是:

我想监听 customizationData 的 choosenOption 设置,并获取将 UILabel 的文本更改为 choosenOption 的价格的标题。

我试图将一个 didSet 添加到 customizationData 但它没有被调用,因为它的一个属性正在改变。不是定制数据本身。

最佳答案

你能做的是可能的,但要触发一个 didSet customizationOptions 你需要改变它的值,基本上有两种方式:

  • 如果customizationOptions是一个引用类型,你需要用另一个引用来改变它
  • 如果 customizationOptions 是一个值类型,例如 Array,如果您更改其中的值,也应该调用 didSet,因为数组完全改变了结构。

为了更好地理解这里有一个例子。
使用值类型:

class Mine {
    var list: [String] = ["Hello"] {
        didSet {
            print("Array changed \(list)")
        }
    }
}

var mine = Mine()

mine.list.append("World") //Array changed ["Hello", "World"]

使用引用类型:

class Mine {
    var list: NSArray = ["Hello"] {
        didSet {
            print("Array changed \(list)")
        }
    }
}

var mine = Mine()
mine.list.adding("World")
 //Doesn't print nothing
mine.list = ["World"]
//print World

关于ios - 当其中一个属性发生变化时,监听数据模型数组中的更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46404616/

相关文章:

ios - 设置是否没有观察模型属性的变化 - Swift

properties - Kotlin 中是否有 didSet/willSet 模拟?

swift - 在 Swift 中实现变量属性属性观察器

ios - 如何在 MVVM 模型中使用 MKMapViewDelegate 方法

ios - EXC_BAD_ACCESS w/OpenCV `cv::aruco::detectMarkers()` 在 IOS 上

ios - 按钮高亮状态的延迟

ios - 自定义 Collection View 布局崩溃

macos - swift 错误 "Immutable value only has mutating members"

ios - didDeselectRowAtIndexPath 未从 Storyboard添加到 UIViewController 的 UITableViewController 调用

ios - 如何在 iphone 中点击应用程序图标时清除角标(Badge)计数器?