How to Remove All Subviews of a UiView – XCode iOS

Use the following code if you need to remove all subviews of a UiView, for ex. to remove all subviews of a scroll view.

1
2
3
4
for (id viewToRemove in [self.scrollView subviews]){
if ([viewToRemove isMemberOfClass:[UIView class]])
[viewToRemove removeFromSuperview];
}
Namit Gupta

iOS Consultant at @RapidCircle. Passionate about Mobile Apps. Loves to Design. You can reach him on his social profiles below.

Comments 3

    1. Thanks for this Erik. This does the job in single line. Excellent find. Cheers.

      To rewrite the above code in same format, it would look like –

      1
      [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
  1. hi! I’m using self.view.addSubview(MxyView(frame: CGRectMake(CGFloat(7), CGFloat(175), 70, 100))) to dynamically add a subview. How do I remove it later?

Leave a Reply