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

required initialiser setup to set a property always

我有这个自定义视图。这个视图总是需要用一个注解来实例化。

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

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

如何解决这个问题??

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

您可以在 self.annotation 赋值后移动配置函数

如果您愿意,可以只用一个初始值设定项替换 override init(frame: CGRect)required convenience init(with annotation: Annotation)

init(frame: CGRect = .zero, with annotation: Annotation) {
    super.init(frame: frame)
    self.annotation = annotation
    configure()
}