Removing Arranged Subviews from UIStackView Crashes App

This function seems to fix it for me:

extension UIStackView {

    func safelyRemoveArrangedSubviews() {

        // Remove all the arranged subviews and save them to an array
        let removedSubviews = arrangedSubviews.reduce([]) { (sum, next) -> [UIView] in
            self.removeArrangedSubview(next)
            return sum + [next]
        }

        // Deactive all constraints at once
        NSLayoutConstraint.deactivate(removedSubviews.flatMap({ $0.constraints }))

        // Remove the views from self
        removedSubviews.forEach({ $0.removeFromSuperview() })
    }
}

[self.headerStackView.arrangedSubviews each:^(UIView *subview) {
    [self.headerStackView removeArrangedSubview:subview]; // <-- Removes Constraints as well
    [subview removeConstraints:subview.constraints];//  <--- Constraints will be invalid or non existing
    [subview removeFromSuperview];
}];

Try this:

while let first = stackView.arrangedSubviews.first {
        stackView.removeArrangedSubview(first) 
        first.removeFromSuperview()
}

Tags:

Objective C