如何设置 UIStackView 的 cornerRadius?

How can I set the cornerRadius of a UIStackView?

我正在更新我的应用程序以使用 UIStackViews,现在大多数人应该已经更新到 iOS9。

在旧版本中,我制作了一个由两个UITextField 组成的UIView,并设置了它的layer.cornerRadius 属性。

在新版本中,我创建了一个由相同的两个 UITextField 组成的 UIStackView,而不是 UIView。当我尝试设置它的 layer.cornerRadius 属性 时,似乎什么也没有发生。文档似乎没有任何 helpful/relevant 信息。

UIStackView 只是管理其排列视图的位置和大小,cornerRadius 没有任何作用。尝试在stackView下面添加一个自定义视图,并设置它的cornerRadius。

在 stackview 的父视图上添加 cornerRadius 并启用父视图的 clipsToBounds 属性,以便子视图被限制在父视图的边界内。

您可以使用这样的扩展程序:

extension UIStackView {
    func customize(backgroundColor: UIColor = .clear, radiusSize: CGFloat = 0) {
        let subView = UIView(frame: bounds)
        subView.backgroundColor = backgroundColor
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        insertSubview(subView, at: 0)

        subView.layer.cornerRadius = radiusSize
        subView.layer.masksToBounds = true
        subView.clipsToBounds = true
    }
}

如果您想为 StackView 提供 backgroundColor、CornerRadius 和 Shadow:

extension UIStackView {
func insertCustomizedViewIntoStack(background: UIColor, cornerRadius: CGFloat, shadowColor: CGColor, shadowOpacity: Float, shadowRadius: CGFloat) {
        let subView = UIView(frame: bounds)
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        subView.layer.cornerRadius = cornerRadius
        subView.backgroundColor = background
        subView.layer.shadowColor = shadowColor
        subView.layer.shadowOpacity = shadowOpacity
        subView.layer.shadowOffset = .zero
        subView.layer.shadowRadius = shadowRadius
        insertSubview(subView, at: 0)
    }
}

如果您想为 StackView 提供 backgroundColor、CornerRadius、borderColor 和边框宽度:

extension UIStackView {
     func insertViewIntoStack(background: UIColor, cornerRadius: CGFloat, borderColor: CGColor, borderWidth: CGFloat) {
        let subView = UIView(frame: bounds)
        subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        subView.layer.cornerRadius = cornerRadius
        subView.backgroundColor = background
        subView.layer.borderColor = borderColor
        subView.layer.borderWidth = borderWidth
        insertSubview(subView, at: 0)
    }
    }

如果您在 Interface Builder 中,您可以执行以下操作:

  1. 将您的 StackView 嵌入到视图中。 (菜单 -> 编辑器 -> 嵌入 -> 查看)

  2. 添加约束,使 StackView 完全约束到新的 superView。

小心! xCode 非常具有误导性,因为如果您正在查看显示约束的导航器(左侧),您可以认为“bottom = stackView.bottom”意味着它们完全对齐。但不是! xCode 默认使用标准约束。您在 xib 的图形显示中看到它,但它很微妙且令人困惑。查看检查器(右侧),其中包含约束的详细信息,您会看到常量是“标准”。将其更改为 0!

  1. 在视图中选中 clipToBounds。 (检查员,朝向底部)

  2. 将您想要的角半径添加到视图中。 (检查员,向上)

如果您的 StackView 在 运行 时间动态调整大小,则此处使用 subView 的答案会有问题。如果您使用带有连接到 StackView 的约束的超级视图 (View),这不是问题。

如果这是您正在执行的特定布局中的一个因素,还请注意您的超级视图中的背景颜色。还有影子,正如这里其他答案中提到的那样。

如果我设置

,它对我有用

stackView.layer.cornerRadius=5

只要将子视图的backgroundColor设置为.clear

在我的例子中,stackView 的 backgroundColor 负责内部视图的背景颜色,所以它适合我。