Overriding UIStackView background color variable

159 views Asked by At

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?

1

There are 1 answers

10
Leo Dabus On

You can't use extension to override a class property. You need to subclass UIStackView if you would like to override any property or method.

From the docs:

Extensions can add new functionality to a type, but they can’t override existing functionality