I am almost new to Programmatic UI.
I have been creating some custom UI components for my projects but when I check people's projects I found the way I create UI components is different than theirs.
The codes completely make the same function but in different ways.
What is the difference between these two codes?
func makeLabel(withAlignment alignment: NSTextAlignment,
withFontSize fontSize: CGFloat) -> UILabel {
let label = UILabel()
label.textAlignment = alignment
label.font = UIFont.systemFont(ofSize: fontSize,
weight: .bold)
label.textColor = .label
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.9
label.lineBreakMode = .byTruncatingTail
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
init(textAlignment: NSTextAlignment,
fontSize: CGFloat) {
super.init(frame: .zero)
self.textAlignment = textAlignment
self.font = UIFont.systemFont(ofSize: fontSize,
weight: .bold)
}
private func configure() {
self.textColor = .label
self.adjustsFontSizeToFitWidth = true
self.minimumScaleFactor = 0.9
self.lineBreakMode = .byTruncatingTail
self.translatesAutoresizingMaskIntoConstraints = false
}
To call them in my VC is the same way.
So the question is which way is better for me to create custom UIs? Are there any pros or cons of these two technics?
CodePudding user response:
The first one is just a helper, you created a function that Return an UILabel
The Second one is a CustomView, it can contain a label, but it can also be composed of several elements, an image label for example
In a custom view, you can also override methods like drawRect or add some other components: for example
var isSelected {
didSet {
//do something
}
}