【发布时间】:2018-10-26 12:58:36
【问题描述】:
我尝试继承 UIStackView 并添加一些我想要的控件。我添加了一个 UIView 作为容器,所有其他的视图,如 UILabel、UIButton、UIImageView 等,都会作为子视图添加到容器中。
class UIButtonHeaderView: UIStackView {
// MARK: - Properties
var container: UIView!
var titleLabel: UILabel!
// MARK: - Initialization
private func setUp() {
// Set container.
container = UIView()
container.backgroundColor = .blue
addArrangedSubview(container)
// Set label.
titleLabel = UILabel()
container.addSubview(titleLabel)
titleLabel.translatesAutoresizingMaskIntoConstraints = false
titleLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor).isActive = true
titleLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor).isActive = true
titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: container.trailingAnchor).isActive = true
titleLabel.widthAnchor.constraint(greaterThanOrEqualToConstant: 0).isActive = true
titleLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 0).isActive = true
titleLabel.text = "This is just a simple test!!"
titleLabel.backgroundColor = .green
titleLabel.textColor = .red
titleLabel.sizeToFit()
}
override init(frame: CGRect) {
super.init(frame: frame)
setUp()
}
required init(coder: NSCoder) {
super.init(coder: coder)
setUp()
}
}
代码运行良好,但替换时出现问题
var container: UIView!
var titleLabel: UILabel!
与
weak var container: UIView!
weak var titleLabel: UILabel!
我认为类UIButtonHeaderView及其属性(container和titleLabel)的实例可能存在引用循环问题,所以我尝试在var前面添加weak,导致我的App崩溃。
Xcode 告诉我这一行
container.backgroundColor = .blue
错误信息出错了
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
好像行
container = UIView()
创建UIView类的实例失败,所以container为nil,导致App崩溃,不知道是什么原因。
【问题讨论】:
-
不相关的注意:你通常不应该在这里继承
UIStackView。你应该继承UIView并添加一个UIStackView。这并不是真正的“一种堆栈视图”(IS-A)。这是一个标题视图,恰好使用堆栈视图进行布局(HAS-A)。您通常应该避免子类化不是为它设计的 UIKit 类(如果它是为子类设计的,那么文档通常会包含“子类化注释”之类的部分或以其他方式讨论子类化)。 -
另外,你应该避免使用
UI前缀作为你的类名;它会起作用,但你的类不是 UIKit 的一部分,所以它违反了约定。
标签: ios swift uilabel uistackview subclassing