swift - 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()
}
}
解决方案
一切都是正确的。您创建了 DetailProductView 的实例,但从未为其product
属性设置任何值。因此 didSet 从未被调用(因为你没有设置任何东西)。
如果你想调用它,你应该为这个属性设置任何值。
推荐阅读
- python - 如何读取 Python 中给出的输入数量
- mongodb - 如何使用golang在mongodb中批量插入
- python - 带有 tkinter 的 Windows
- flutter - 如何将参数传递给 onInit 方法
- sql - 在 SQL 中的特殊字符之后和之前将所有内容作为单独的列获取
- javascript - Google表格/应用程序脚本:在特定文件夹中创建新电子表格的功能
- discord.js - Discord.js 在 1 个命令中添加/删除角色
- node.js - 打字稿导入别名子模块而不暴露
- angular - 依次执行异步函数,等待每个函数执行完毕
- unity3d - 当我点击 E 并且光线投射没有命中对象时,我收到此错误消息:NullReferenceException:Object reference not set to an instance of an object