How can I set the cornerRadius of a UIStackView?

You can use an extension like this:

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
    }
}

add cornerRadius on stackview's superview and enable clipsToBounds property of the superview so that the subviews are confined to the bounds of the superview.


UIStackView just manages the position and size of its arranged views, the cornerRadius has no effect. Try to add a custom view below the stackView and set the cornerRadius of it.


If you want to provide backgroundColor, CornerRadius and Shadow to StackView:

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)
    }
}

If you want to provide backgroundColor, CornerRadius , borderColor and border width to StackView:

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)
    }
    }