UIStackView Hide View Animation UIStackView Hide View Animation ios ios

UIStackView Hide View Animation


Just had the same issue.The fix is adding stackView.layoutIfNeeded() inside the animation block. Where stackView is the container of the items you're wishing to hide.

UIView.animate(withDuration: DiscoverHeaderView.animationDuration,                   delay: 0.0,                   usingSpringWithDamping: 0.9,                   initialSpringVelocity: 1,                   options: [],                   animations: {                        clear.isHidden = hideClear                        useMyLocation.isHidden = hideLocation                        stackView.layoutIfNeeded()                    },                   completion: nil)

Not sure why this is suddenly an issue in iOS 11 but to be fair it has always been the recommended approach.


It's already mentioned in the comments of the accepted answer, but this was my problem and it's not in any of the answer here so:

Make sure to never set isHidden = true on a view that is already hidden. This will mess up the stack view.


Swift 4 Extension:

// MARK: - Show hide animations in StackViewsextension UIView {func hideAnimated(in stackView: UIStackView) {    if !self.isHidden {        UIView.animate(            withDuration: 0.35,            delay: 0,            usingSpringWithDamping: 0.9,            initialSpringVelocity: 1,            options: [],            animations: {                self.isHidden = true                stackView.layoutIfNeeded()            },            completion: nil        )    }}func showAnimated(in stackView: UIStackView) {    if self.isHidden {        UIView.animate(            withDuration: 0.35,            delay: 0,            usingSpringWithDamping: 0.9,            initialSpringVelocity: 1,            options: [],            animations: {                self.isHidden = false                stackView.layoutIfNeeded()            },            completion: nil        )    }}}