Я всегда программно создавал свой пользовательский интерфейс, и недавно я начал больше узнавать о loadView (). Я понял, что когда я использовал loadView (), я писал бы код следующим образом:
override func loadView() {
super.loadView()
let EarningsView = UIView()
let EarningsLabel = UILabel()
EarningsView.translatesAutoresizingMaskIntoConstraints = false
EarningsLabel.translatesAutoresizingMaskIntoConstraints = false
let earningsText = NSAttributedString(string: "My Earnings", attributes: self.stringAttrib)
EarningsLabel.attributedText = earningsText
EarningsLabel.textColor = .black
EarningsLabel.backgroundColor = .white
EarningsView.addSubview(EarningsLabel)
EarningsView.addViewBorder(borderColor: UIColor.black.cgColor, borderWith: 0.5, borderCornerRadius: 0.0)
EarningsView.backgroundColor = .white
NSLayoutConstraint.activate([
EarningsView.widthAnchor.constraint(equalTo: contentStack.widthAnchor),
EarningsView.topAnchor.constraint(equalTo: contentStack.topAnchor),
EarningsView.centerXAnchor.constraint(equalTo: contentStack.centerXAnchor),
view.addSubview(EarningsView)
}
По сравнению с тем, как я всегда писал:
fileprivate lazy var earningsView : UIView = {
var view = UIView()
let EarningsLabel = UILabel()
EarningsLabel.translatesAutoresizingMaskIntoConstraints = false
let earningsText = NSAttributedString(string: "My Earnings", attributes: self.stringAttrib)
EarningsLabel.attributedText = earningsText
EarningsLabel.textColor = .black
EarningsLabel.backgroundColor = .white
view.addSubview(EarningsLabel)
view.addViewBorder(borderColor: UIColor.black.cgColor, borderWith: 0.5, borderCornerRadius: 0.0)
view.backgroundColor = .white
view.addSubview(EarningsLabel)
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(earningsView)
NSLayoutConstraint.activate([
earningsView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
earningsView.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
earningsView.widthAnchor.constraint(equalTo: self.view.widthAnchor),
earningsView.heightAnchor.constraint(equalTo: self.view.heightAnchor,multiplier: 0.20),
])
Это в один раз лучше, чем Другой? Или это больше личного предпочтения.