我有一个称为BaseView的customView,它具有一个contentView,在contentView中,我要在覆盖init(frame:CGRect)方法中添加所有其他子视图(UILabel,UIButton等)。
现在我的BaseView有10个子类,它们也重写init(frame:CGRect)并调用基类init(frame:CGRect)方法。
这里所有子类的UI都与其BaseView相似,现在BaseView的一个子类不希望该基类中包含某些UI元素,但是我仍然需要调用superview init(frame:CGRect)。如何在不影响其他类的情况下更改代码?
Class BaseView: UIView {
let contentView = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
let lbl1 = UILabel()
contentView.addSubView(lbl1)
let lbl2 = UILabel()
contentView.addSubView(lbl2)
self.addSubView(contentView)
}
Class subView1: BaseView {
override init(frame: CGRect) {
super.init(frame: frame)
// This class will show lbl1, lbl2 and lbl3 in the contentview
let lbl3 = UILabel()
contentView.addSubView(lbl3) // this contentview is BaseView's ContentView
}
// Similarly I have around 10 Subclasses of BaseView which is adding some UI Element to
baseview's contentView
// Question here is, below I am going to create another subclass of BaseView, But I don't
want to show lbl1 and lbl2 which is created in my BaseView's contentview
Class myView: BaseView {
// this class should not show the base class uilement lbl1 and lbl2, It should show only
lbl4 which is created by this class only
override init(frame: CGRect) {
super.init(frame: frame)
let lbl4 = UILabel()
contentView.addSubView(lbl4) // this contentview is BaseView's ContentView
}
代替调用super.init
,您只需在子类中添加所需的代码,如下所示:
class myView: BaseView {
override init(frame: CGRect) {
addSubview(contentView)
let lbl4 = UILabel()
contentView.addSubView(lbl4)
}
}