[英]UIButton's layer.cornerRadius removes visibility of button title
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. 我为按钮添加了一个自定义类,在其中设置了拐角半径(以保存多个VC的代码),但是一旦设置,按钮标题便消失了。 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. 我的按钮背景是带有alpha的灰色。 I have tried to play with the .isOpaque setting but got no luck getting the title back.
我曾尝试使用.isOpaque设置,但运气不佳,无法获得冠军头衔。 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
要修复布局,您需要调用
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.