14

I have an iPhone application that uses a timer and at every time interval it creates some UILabel controls and adds them into a UIScrollView.

What I want to do is to clear the UIScrollView every time interval before it puts the UILabel controls into the UIScrollView.

How can I clear the contents of the UIScrollView?

Mel
  • 5,837
  • 10
  • 37
  • 42
Joy
  • 1,609
  • 3
  • 16
  • 28

6 Answers6

46
for (UIView *subview in scrollView.subviews) {
  [subview removeFromSuperview];
}
  • 21
    or in one line: [scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; – Vladimir Jun 17 '10 at 15:14
  • This answer is wrong because the scroll indicators are also subviews of the scrollView. – trapper Jul 11 '16 at 07:38
  • I know this is old but I am a bit confused. I was experiencing a problem when adding/removing content dynamically to the uiscrollview it was mixing up old with new content and I was looping thru the subviews and removing them all with for (int i = 0; i < scrollView.subviews.count; i++) instead of this. Isn't it the same in the end? – CJ_COIMBRA Feb 28 '17 at 12:59
15

You will also remove the scrollbar with the above solution. To solve this, you may ask whether the subview about to be removed is a UIImageView instance. Obviously, you will need to do more checks if you happen to have your own UIImageViews in the scroll view.

for (UIView *subview in scrollView.subviews) {
  if(![subview isKindOfClass:[UIImageView class]])
    [subview removeFromSuperview];
}
Community
  • 1
  • 1
Oliver
  • 424
  • 6
  • 11
2

I typically go with a one liner like this: in case you're interested..

while(scrollView.subviews.count > 0) [[scrollView.subviews objectAtIndex:0] removeFromSuperview];
Jacksonkr
  • 31,583
  • 39
  • 180
  • 284
0

In one line

[_ui_scroll.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
Sirko
  • 72,589
  • 19
  • 149
  • 183
isanjosgon
  • 1,829
  • 1
  • 13
  • 12
0

SWIFT:

 for  subview in self.scrollView.subviews
        {
             subview.removeFromSuperview()
        }
Yogesh Lolusare
  • 2,162
  • 1
  • 24
  • 35
0

Its Very simple just write this code inside your loop where dynamic structure is creating and changing it's content frequently.

[subview removeFromSuperview];
Kjuly
  • 34,476
  • 22
  • 104
  • 118