Skip to content

Instantly share code, notes, and snippets.

@Deub27
Created November 25, 2017 14:00
Show Gist options
  • Save Deub27/5eadbf1b77ce28abd9b630eadb95c1e2 to your computer and use it in GitHub Desktop.
Save Deub27/5eadbf1b77ce28abd9b630eadb95c1e2 to your computer and use it in GitHub Desktop.
Remove all arranged subviews from UIStackView at once
import UIKit
extension UIStackView {
func removeAllArrangedSubviews() {
let removedSubviews = arrangedSubviews.reduce([]) { (allSubviews, subview) -> [UIView] in
self.removeArrangedSubview(subview)
return allSubviews + [subview]
}
// Deactivate all constraints
NSLayoutConstraint.deactivate(removedSubviews.flatMap({ $0.constraints }))
// Remove the views from self
removedSubviews.forEach({ $0.removeFromSuperview() })
}
}
@yasirmturk
Copy link

@finebel
Copy link

finebel commented Aug 20, 2020

Please corret me if I'm wrong but from my understanding you could simply do the following to remove all arrangedSubviews:

extension UIStackView {
    func removeAllArrangedSubviews() {
        arrangedSubviews.forEach {
            self.removeArrangedSubview($0)
            NSLayoutConstraint.deactivate($0.constraints)
            $0.removeFromSuperview()
        }
    }
}

@uvios
Copy link

uvios commented Sep 17, 2020

Worked like a charm 👍

@igorleonovich
Copy link

igorleonovich commented Feb 27, 2024

Just the SnapKit version:

import UIKit
import SnapKit

extension UIStackView {
    
    func removeArrangedSubviews() {
        guard !arrangedSubviews.isEmpty else { return }
        let subviewsToRemove = arrangedSubviews.reduce([]) { allSubviews, subview -> [UIView] in
            self.removeArrangedSubview(subview)
            return allSubviews + [subview]
        }
        subviewsToRemove.forEach { subview in
            subview.snp.removeConstraints()
            subview.removeFromSuperview()
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment