为堆栈视图中嵌入的视图设置层的 cornerRadius 会产生意想不到的结果
Setting cornerRadius of layer for a view embedeed in stack view gives unexpected results
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
}
我在堆栈视图中嵌入了四个 UIButton,正如您在屏幕截图中看到的那样,所有按钮的形状都不正确,它们应该看起来像一个圆圈。
我怀疑我应该在我的代码中的其他地方设置 cornerRadius
,但是在哪里?
为了让它们看起来像一个圆,您的边界必须是 正方形。您的按钮似乎不是这种情况(宽度大于高度)。
您可以为按钮添加一些约束以保持 1/1 的比例。
除此之外,您将其设置在正确的位置。
四舍五入到 with/2
将完全圆顶和底边(眼睛形状)
四舍五入到 height/2
将完全四舍五入左右两侧(像这样 ()
)
因此,如果您想要圆形,则需要确保 width
和 height
大小与正方形相同。
为了自动完成,您可以使用自动布局,stackView 将负责调整大小:
self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(equalTo: self.widthAnchor).isActive = true
确保只执行一次以避免重复。
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
}
我在堆栈视图中嵌入了四个 UIButton,正如您在屏幕截图中看到的那样,所有按钮的形状都不正确,它们应该看起来像一个圆圈。
我怀疑我应该在我的代码中的其他地方设置 cornerRadius
,但是在哪里?
为了让它们看起来像一个圆,您的边界必须是 正方形。您的按钮似乎不是这种情况(宽度大于高度)。
您可以为按钮添加一些约束以保持 1/1 的比例。
除此之外,您将其设置在正确的位置。
四舍五入到 with/2
将完全圆顶和底边(眼睛形状)
四舍五入到 height/2
将完全四舍五入左右两侧(像这样 ()
)
因此,如果您想要圆形,则需要确保 width
和 height
大小与正方形相同。
为了自动完成,您可以使用自动布局,stackView 将负责调整大小:
self.translatesAutoresizingMaskIntoConstraints = false
self.heightAnchor.constraint(equalTo: self.widthAnchor).isActive = true
确保只执行一次以避免重复。