Reputation: 2193
I'm creating a custom UILabel
class. The reason why is because I want to adjust the properties of a Label with a Constants
class. Modifying properties in IB can become cumbersome once the primary color of the app changes. Anyways this is my custom UILabel class:
@IBDesignable class FormTitleLabel: UILabel {
override var font: UIFont! {
get {
return UIFont.systemFont(ofSize: 36, weight: .heavy)
} set {
super.font = font
}
}
}
This causes the label to appear cut-off:
I can fix this by using the following code:
@IBDesignable class FormTitleLabel: UILabel {
override var font: UIFont! {
get {
return UIFont.systemFont(ofSize: 36, weight: .heavy)
} set {
super.font = font
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
setup()
}
override func awakeFromNib() {
super.awakeFromNib()
setup()
}
private func setup() {
self.font = UIFont.systemFont(ofSize: 36)
}
}
Why does this solution work?
Upvotes: 0
Views: 349
Reputation: 40030
This code is simply wrong:
override var font: UIFont! {
get {
return UIFont.systemFont(ofSize: 36, weight: .heavy)
} set {
super.font = font
}
}
You're always returning font A
, but internally setting font B
. View drawing functions check the font of the label to draw text and they use font A
, although in reality, they should use font B
. That's why you have this weird behaviour.
Upvotes: 2