7

I need to remove image subviews from a ScrollView and I tried removing from the array of subviews but that is an NSArray which is immutable.

How can a subview be removed from the scrollviews array of subviews?

6 Answers 6

35
    NSArray *viewsToRemove = [scrollView subviews];
    for (UIView *v in viewsToRemove) [v removeFromSuperview];
1
  • 2
    Doing so you will also remove the scroll indicators... Seems we have to check the type of the view to be removed.
    – Tim Autin
    Jun 15, 2013 at 0:11
12

You can do this,

[[scrollView subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
5

This will remove all subviews of a UIScrollView but its scroll indicators: _scrollView.showsHorizontalScrollIndicator = _scrollView.showsVerticalScrollIndicator = NO; [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; _scrollView.showsHorizontalScrollIndicator = _scrollView.showsVerticalScrollIndicator = YES;

1
  • Apparently [_scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)]; will remove all UIScrollView subviews, including its scroll indicators. Hiding the scroll indicators before removing all subviews from scrollview will ensure scroll indicators are not removed from scrollview.
    – calinb
    Oct 12, 2015 at 14:19
2
for (UIView *v in [scrollView subviews]) {
    [v removeFromSuperview];       
}
1

Call -removeFromSuperview on the subview.

1

Swift

for subview in scrollView.subviews {
    subview.removeFromSuperview()
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.