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

IphoneObjective CIosUikit

Iphone Problem Overview


I was thinking maybe something like this might work:

for (UIView* b in self.view.subviews)
{
   [b removeFromSuperview];
}

I want to remove every kind of subview. UIImages, Buttons, Textfields etc.

Iphone Solutions


Solution 1 - Iphone

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

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

Solution 2 - Iphone

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

Identical version in Swift.

Solution 3 - Iphone

Swift:

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

Solution 4 - Iphone

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

Solution 5 - Iphone

For Swift 4+.You can make a extension to UIView. Call it whenever necessary.

extension UIView {
    func removeAllSubviews() {
        subviews.forEach { $0.removeFromSuperview() }
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser440096View Question on Stackoverflow
Solution 1 - IphoneMaxView Answer on Stackoverflow
Solution 2 - IphonelclView Answer on Stackoverflow
Solution 3 - IphonemixelView Answer on Stackoverflow
Solution 4 - IphonespikeeView Answer on Stackoverflow
Solution 5 - IphoneishwardgretView Answer on Stackoverflow