Kex*_*Ari 5 initialization uiview ios swift
我正在尝试为UIView创建自定义init方法。代码如下:
convenience init(frame: CGRect, tutorProfileImageURL: String?) {
self.tutorProfileImageURL = tutorProfileImageURL
super.init(frame: frame)
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
_ = Bundle.main.loadNibNamed("TutorArrivedAlertView", owner: self, options: nil)?[0] as! UIView
self.addSubview(customView)
customView.frame = self.bounds
tutorImageView.layer.cornerRadius = tutorImageView.frame.size.height/2
tutorImageView.clipsToBounds = true
}
Run Code Online (Sandbox Code Playgroud)
但是我得到了错误:
便利的初始化程序必须使用self.init进行委派,而不是使用super.init链接到超类初始化程序
此错误表明,我们不应该将便捷性初始化程序与其父类初始化程序链接在一起。
我们需要调用以下方法
super.init(frame:框架)
在这个方法里面
覆盖init(frame:CGRect)
看起来是这样的:
convenience init(frame: CGRect, tutorProfileImageURL: String?) {
self.init(frame: frame)
self.tutorProfileImageURL = tutorProfileImageURL
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
Run Code Online (Sandbox Code Playgroud)
小智 2
便利初始化器使用他的 init 来实现它。所以只需将最后一行更改为 self.init
convenience init(frame: CGRect, tutorProfileImageURL: String?) {
self.init(frame: frame)
self.tutorProfileImageURL = tutorProfileImageURL
}
Run Code Online (Sandbox Code Playgroud)