I was shocked to learn that ability to set a background color to a UIStackView come only starting from iOS14. In the older versions such attempts are just ignored.
I have to support older versions as well, so I wrote this code to fix the issue:
public extension UIStackView {
private var helperSubview: UIView {
subviews.first(where: { $0.id == "helperSubview" }) ?? {
let hsv = UIView()
hsv.id = "helperSubview"
insertSubview(hsv, at: 0)
hsv.fillSuperview()
return hsv
}()
}
override var backgroundColor: UIColor? {
didSet {
if #available(iOS 14.0, *) {
return
} else {
helperSubview.backgroundColor = backgroundColor
}
}
}
}
The code works just fine.
But there is one strange moment: in iOS14 didSet doesn't fire at all (like we can even don't check #availability). That suits me, this behaviour doesn't cause any problems. But I don't understand why does it behave like that?
You can't use extension to override a class property. You need to subclass
UIStackViewif you would like to override any property or method.From the docs: