Search code examples
iosswiftuistackview

How to change the background color of UIStackView?


Note that in modern iOS you CAN SET THE BACKGROUND COLOR NORMALLY.

historic question:


I tried to change the UIStackView background from clear to white in Storyboard inspector, but when simulating, the background color of the stack view still has a clear color.
How can I change the background color of a UIStackView?


Solution

  • You can't do this – UIStackView is a non-drawing view, meaning that drawRect() is never called and its background color is ignored. If you desperately want a background color, consider placing the stack view inside another UIView and giving that view a background color.

    Reference from HERE.

    EDIT:

    You can add a subView to UIStackView as mentioned HERE or in this answer (below) and assign a color to it. Check out below extension for that:

    extension UIStackView {
        func addBackground(color: UIColor) {
            let subView = UIView(frame: bounds)
            subView.backgroundColor = color
            subView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            insertSubview(subView, at: 0)
        }
    }
    

    And you can use it like:

    stackView.addBackground(color: .red)