I have added a custom class for my buttons where I set corner radius (to save some code for multiple VCs) but once I set it, title from my buttons disappears. You can see I have a button title set and it worked ok before choosing a custom class.
Background of my button is the gray color with alpha. I have tried to play with the .isOpaque setting but got no luck getting the title back. Any idea what could cause this problem?
@IBDesignable class RoundedButton: UIButton {
@IBInspectable var cornerRadius: CGFloat = 8
override func layoutSubviews() {
layer.cornerRadius = cornerRadius
}
}
Edit: Solved! Thanks u/zombie for an explenation!
The title does not show because its frame was not updated.
To fix the layout you need to call super.layoutSubviews
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = cornerRadius
}
Your approach might prevent any update of the radius outside of your variable.
here is a better way to do it:
@IBDesignable class RoundedButton: UIButton {
private var defaultCornerRadius: CGFloat = 8
@IBInspectable var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
override init(frame: CGRect) {
super.init(frame: frame)
cornerRadius = defaultCornerRadius
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
cornerRadius = aDecoder.decodeObject(forKey: "cornerRadius") as? CGFloat ?? defaultCornerRadius
}
override func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(cornerRadius, forKey: "cornerRadius")
}
}
You forget
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = cornerRadius
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.