Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to remove all subviews from you self.view?

People also ask

How do I remove all Subviews from a view in Swift?

By doing . copy(), I could perform the removal of each subview while mutating the self. subviews array. This is because the copied array (subViews) contains all of the references to the objects and is not mutated.

How do I get Subviews in UIView Swift?

If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.


[self.view.subviews makeObjectsPerformSelector: @selector(removeFromSuperview)];

It's identical to your variant, but slightly shorter.


self.view.subviews.forEach({ $0.removeFromSuperview() })

Identical version in Swift.


Swift:

extension UIView {
    func removeAllSubviews() {
        for subview in subviews {
            subview.removeFromSuperview()
        }
    }
}

You can use like this

//adding an object to the view
view.addSubView(UIButton())

// you can remove any UIControls you have added with this code
view.subviews.forEach { (item) in
     item.removeFromSuperview()
}

view is the view that you want to remove everything from. you are just removing every subview by doing forEach