[英]Setting cornerRadius of layer for a view embedeed in stack view gives unexpected results
ModernBoldButton
is a subclass of UIButton
, here is a snippet of it: ModernBoldButton
是UIButton
的子类,下面是它的一个片段:
private func commonInit() {
insertSubview(blurView, at: 0)
if let imageView = imageView {
bringSubviewToFront(imageView)
}
if let titleLabel = titleLabel {
bringSubviewToFront(titleLabel)
}
backgroundColor = .clear
clipsToBounds = true
}
override func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width / 2
}
I have four UIButton's embedeed in stack view and as you can see on the screenshot, all of the buttons have incorrect shapes, they should look like a circle. 我在堆栈视图中嵌入了四个UIButton,如屏幕截图所示,所有按钮的形状都不正确,它们应该看起来像一个圆圈。
I suspect that I should set the cornerRadius
somewhere else in my code, but where? 我怀疑我应该在代码中的其他地方设置
cornerRadius
,但是在哪里?
In order for them to look like a circle, your bounds must be a square . 为了使它们看起来像圆形,您的边界必须是正方形 。 It appears that this is not the case for your buttons (the width is larger than the height).
看来您的按钮不是这种情况(宽度大于高度)。
You could add some constraints to your buttons in order to maintain a 1/1 ratio. 您可以在按钮上添加一些约束,以保持1/1的比率。
Other than that, you're setting it in the right place. 除此之外,您还需要将其设置在正确的位置。
Rounding to with/2
will completely rounded top and bottom sides (eye shape 👁) Rounding to height/2
will completely rounded left and right sides (like this ()
) 取整为
with/2
将使顶侧和底侧完全变圆(眼睛形状👁)取整为height/2
将使左侧和右侧完全变圆(像这样()
)
So if you want a circle, you need to make sure both width
and height
sizes are the same like a square. 因此,如果您想要一个圆,则需要确保
width
和height
大小都相同,例如正方形。
In order to doo it automatically, you can use autolayout and the stackView will take care of the sizing: 为了自动完成它,您可以使用自动布局,stackView将负责调整大小:
self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(equalTo: self.widthAnchor).isActive = true
Make sure to do it just once to avoid duplications. 确保只做一次以避免重复。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.