89

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.

pkamb
  • 33,281
  • 23
  • 160
  • 191
  • 1
    That will work. You might have to do it kind of recursively if you have several tiers of subviews... or maybe not. I'm not sure what you want to do this for. – Dustin Aug 09 '12 at 17:59
  • That works? I thought that `b` would be promptly removed from the `subviews` array, causing a mutation within a fast enumeration loop, which is forbidden. – Mazyod Aug 09 '12 at 18:02
  • 2
    @Mazyod check subviews property: @property(nonatomic, readonly, copy) NSArray *subviews - it is declared as copy, so when we are deleting subviews we do not modify that array (cause it's a copy). – Max Aug 09 '12 at 18:14
  • 1
    @Max: That's incorrect. The `copy` specifier means that it makes a copy _when set_; nothing is specified about getting. It is quite likely that a copy is returned, but that's not part of the property definition. – jscs Aug 09 '12 at 18:43
  • @W'rkncacnter agree, you're right that copy keyword has nothing to do with get value (but I think it is implied). – Max Aug 09 '12 at 18:57
  • possible duplicate of [Remove all subviews?](http://stackoverflow.com/questions/2156015/remove-all-subviews) – mixel Sep 08 '15 at 16:50
  • Duplicate --> http://stackoverflow.com/questions/2156015/remove-all-subviews – Kakshil Shah Sep 09 '16 at 04:21

5 Answers5

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

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

Max
  • 16,679
  • 4
  • 44
  • 57
23
self.view.subviews.forEach({ $0.removeFromSuperview() })

Identical version in Swift.

lcl
  • 1,045
  • 11
  • 13
7

Swift:

extension UIView {
    func removeAllSubviews() {
        for subview in subviews {
            subview.removeFromSuperview()
        }
    }
}
mixel
  • 25,177
  • 13
  • 126
  • 165
3

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

spikee
  • 61
  • 4
0

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

extension UIView {
    func removeAllSubviews() {
        subviews.forEach { $0.removeFromSuperview() }
    }
}
ishwardgret
  • 1,068
  • 8
  • 10