在 iOS 14 之前,直接给 UIStackView 添加背景色是无效果的,得通过添加一个子 view 方式来实现,如下面的代码

let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
let backgroundView = UIView(frame: .zero)
backgroundView.backgroundColor = Color.red
backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
backgroundView.tag = 1
stackView.insertSubview(backgroundView, at: 0)

iOS 14 系统已经支持直接给 UIStackView 添加背景色了

let stackView = UIStackView(frame: .zero)
stackView.backgroundColor = Color.red

我们可以给 UIStackView 添加一个扩展来封装这个细节

extension UIStackView {
    func backgroundColor(_ color: UIColor) -> Void {
        if #available(iOS 14.0, *) {
            backgroundColor = color
        } else {
            if let view = viewWithTag(1) {
                view.backgroundColor = color
            } else {
                let backgroundView = UIView(frame: bounds)
                backgroundView.backgroundColor = color
                backgroundView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
                backgroundView.tag = 1
                insertSubview(backgroundView, at: 0)
            }
        }
    }
}

如此,就可以直接通过 stackview.backgroundColor(UIColor.red) 来调用了。