addArrangedSubview without animations

i0S Swift Issue

Question or problem in the Swift programming language:

I add views to a TZStackView (which should be basically the same as a UIStackView, but with a fallback for older versions) like this:

stackView.addArrangedSubview(subview)

the stackView and the subview are of dynamic size (auto-layout) and resize themselves. However, this happens with an animation (I think due to addArrangedSubview, it does not happen if I add it as subview and set constraints). Is there a way to deactivate the animations?

How to solve the problem:

Solution 1:

Disabling animations while adding arranged views to a UIStackView does not work properly in iOS 9.

The solution is to perform the addition separately from the layout:

// Add all views first.

for view in views {
    stackView.addArrangedSubview(view)
}

// Now force the layout in one hit, sans animation.

UIView.performWithoutAnimation {
    stackView.setNeedsLayout()
    stackView.layoutIfNeeded()
}

Tested on iOS 9.3, Xcode 8.3.2.
Not tested on iOS 10 or 11 yet.

Solution 2:

UIView performWithoutAnimation: will execute its block argument without animation:

UIView.performWithoutAnimation {
    stackView.addArrangedSubview(subview)
}

Hope this helps!