UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview? UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview? ios ios

UIStackView : Is it really necessary to call both removeFromSuperView and removeArrangedSubview to remove a subview?


No, just call subview.removeFromSuperview()

/* Removes a subview from the list of arranged subviews without removing it as a subview of the receiver.    To remove the view as a subview, send it -removeFromSuperview as usual; the relevant UIStackView will remove it from its arrangedSubviews list automatically. */open func removeArrangedSubview(_ view: UIView)


In iOS 12.0, You need to use

stackView.arrangedSubviews[index].removeFromSuperview()

If you use removeArrangedSubview, there is a bug where the view at the specified index removed, but the view I want to clear appears at CGPoint(x: 0, y: 0).

Hope this help someone.


Hacking With Swift provides a pretty good example and explanation, using Web views in this case.

The reason is that you can remove something from a stack view's arranged subview list then re-add it later, without having to recreate it each time – it was hidden, not destroyed. We don't want a memory leak, so we want to remove deleted web views entirely. If you find your memory usage ballooning, you probably forgot this step!

https://www.hackingwithswift.com/read/31/4/removing-views-from-a-uistackview-with-removearrangedsubview