【发布时间】:2020-06-16 05:42:06
【问题描述】:
我有一个名为 BaseView 的 customView,它有一个 contentView,在 contentView 中,我在 override init(frame: CGRect) 方法中添加了所有其他子视图(UILabel、UIButton 等)。
现在我的 BaseView 有 10 个子类,它们也覆盖 init(frame: CGRect) 并调用基类 init(frame: CGRect) 方法。
这里我所有的子类看起来都类似于它的BaseView UI,现在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
}
【问题讨论】: