需要进行初始化程序设置以始终设置属性

问题描述

我有这个自定义视图。此视图始终需要使用注释实例化。

class MapImageLocationPin: UIView {
    //MARK: - Properties
    private var annotation: Annotation!
    
    //MARK: - Init
    override init(frame: CGRect) {
        super.init(frame: frame)
        configure()
    }
    
    required convenience init(with annotation: Annotation) {
        self.init(frame: .zero)
        self.annotation = annotation
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //MARK: - Configure view
    private func configure() {
        print("Pin initialised! \(annotation.title)")
    }
}

上述设置失败(崩溃,值为nil),因为在设置注释之前,在self.init中调用了configure()。

如何解决这个问题?

解决方法

required convenience init(with annotation: Annotation) {
   self.init(frame: .zero)
   self.annotation = annotation
   self.configure()
}

您可以在分配self.annotation后移动配置功能

,

如果愿意,可以用一个初始化程序替换async/awaitoverride init(frame: CGRect)

required convenience init(with annotation: Annotation)