Animate StackViews

Table of Content

Animate StackViews

I ran into a weird bug today. I was working on my app’s settings view controller. I have some stack views set up to look like table views since stack views allow for easy, reliable animation when toggling their children’s visibility property… Or so I thought!

This was happening to me:

As you can see, sometimes toggling the .isHidden of the children properties broke the animation. The fix is slightly more obscure than you might think.

I was lucky enough to just happen on the comment on this SO answer.

For me the fix was to check for self.isHidden and not set the value if is is already the same

Conveniently, I already made a convenience method on UIView to make .isHidden easier to reason about:

extension UIView {
    var isVisible: Bool {
        get {
            !isHidden
        }
        set {
            isHidden = !newValue
        }
    }
}

Just adding the additional line in the setter fixed it:

extension UIView {
    var isVisible: Bool {
        get {
            !isHidden
        }
        set {
            guard isHidden != !newValue else { return }
            isHidden = !newValue
        }
    }
}

I know it reads a bit weird with the double negative, but it was that or isHidden == newValue which I think sends the wrong message unless you are really paying attention.

Anyways, it works as it should now (or at least I haven’t managed to break it yet while testing) and the .isVisible is easier to read in code and only makes changes if necessary!

Leave a Reply

Your email address will not be published. Required fields are marked *