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

robola picture robola · May 30, 2016 · Viewed 29.8k times · Source

From the UIStackView Class Reference

In removeArrangedSubview:

To prevent the view from appearing on screen after calling the stack’s removeArrangedSubview: method, explicitly remove the view from the subviews array by calling the view’s removeFromSuperview method.

In arrangedSubview:

Whenever an arranged view’s removeFromSuperview method is called, the stack view removes the view from its arrangedSubview array

From these, it seems that calling just removeFromSuperview is enough to remove a subview and I've been using it like that without problems. I also confirmed the behavior by logging the count of the arrangedSubviews array when removeFromSuperview is called.

A lot of tutorials and comments here on S/O however, say to call both. Is there a reason for this? Or do people just do it because the documentation says so?

Answer

zurakach picture zurakach · Feb 20, 2017

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)