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.

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

Technical Lead iOS @ONEChampionship | Ex-SDE2 @ Halodoc, Ex-iOS Lead @ Vokal. ❤️ Swift, designing pixel-perfect UI and writing clean code. Check my portfolio here.

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 –

      [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