首页 > 解决方案 > UIView 的子类不调用 didSet

问题描述

我有一个名为 BaseView 的 UIView 子类。在 BaseView 的子类中,我使用一些代码创建了 didSet。在 UIViewController 我初始化 BaseView 的这个子类,他没有调用他的 didSet

基本视图代码:

class BaseView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupViews()
    }

    func setupViews() { }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

BaseView 代码的子类:

class DetailProductView: BaseView {

var product: Product? {
    didSet {
        productImage.image = UIImage(named: (product?.productImageName)!)
        productTitle.text = product?.title
        productCompositionLabel.text = product?.description
        productPriceLabel.text = "₽" + product!.productPrice!.stringValue
        productWeightLabel.text = product!.productWeight!.stringValue + "г."
    }
}

UIViewController 代码:

class DetailProductController: UIViewController {

    var product: Product?

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        let productView = DetailProductView(frame: self.view.bounds)
        view.addSubview(productView)
        view.layoutSubviews()
    }
}

标签: swiftuiviewdidset

解决方案


一切都是正确的。您创建了 DetailProductView 的实例,但从未为其product属性设置任何值。因此 didSet 从未被调用(因为你没有设置任何东西)。

如果你想调用它,你应该为这个属性设置任何值。


推荐阅读