如何解决需要进行初始化程序设置以始终设置属性
我有这个自定义视图。此视图始终需要使用注释实例化。
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/await
和override init(frame: CGRect)
:
required convenience init(with annotation: Annotation)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。