`UILabel` 中`textColor` 的延迟实例化会引发错误

lazy instantiation of `textColor` in `UILabel` throws an error

如果我取消注释 self.numberLabel.textColor = UIColor.black,构建会编译但会在模拟器中崩溃。

 lazy public var numberLabel: UILabel = {
        self.numberLabel.textColor = UIColor.black
        return UILabel(frame: CGRect.init(x: 10, y: 40, width: self.bounds.size.width, height: 20))
    }()

The error states: "EXC_BAD_ACCESS".

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

示例片段 - Swift3.x

 lazy public var numberLabel: UILabel = {
    let label = UILabel(frame: CGRect(x: 20, y: 20, width: 200, height: 21))
    label.textColor = UIColor.black
    return label
}()



 override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(numberLabel)
        numberLabel.text = "Good"
}

您在设置之前指的是 numberLabel,最好的方法是:

lazy public var numberLabel: UILabel = {
    let label = UILabel(frame: CGRect.init(x: 10, y: 40, width:     self.bounds.size.width, height: 20))
    label.textColor = UIColor.black
    return label
}()

如你所见,首先"let label = "创建标签,然后可以执行所有初始化(如textcolor),最后我们return标签,分配给惰性属性.