Moshe
Moshe

Reputation: 58087

Remove all the subviews from a UIScrollView?

How do I remove all of the subviews from a UIScrollview?

Upvotes: 48

Views: 28175

Answers (5)

Gui Moura
Gui Moura

Reputation: 1360

Complementing the Swift concise version from a previous answer (Swift 3.0 ready):

_ = scrollView.subviews.filter { $0 is UIImageView }.map { $0.removeFromSuperview() }

Upvotes: 0

koo
koo

Reputation: 2918

Let scrollView be an instance of UIScrollView.

In Objective-C, it's pretty easy. Just call makeObjectsPerformSelector:, like so:

Objective-C:

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

In Swift, you don't get that runtime access, so you have to actually handle the iteration yourself.

Swift:

A concise version, from here:

scrollview.subviews.map { $0.removeFromSuperview() }

A more descriptive way to do this (from here) assumes scrollview.subviews:

let subviews = self.scrollView.subviews
for subview in subviews{
    subview.removeFromSuperview()
}

Upvotes: 127

mylogon
mylogon

Reputation: 2959

In addition to Ricardo de Cillo's, in my case I had a table view that had imageviews in the subviews that I wanted to remove.

for (UIView *v in self.tableview.subviews) {
  if ([v isKindOfClass:[UIImageView class]]) {
    [v removeFromSuperview];
  }
}

The removal of the ! in the if command, and change scrollview to self.tableview removed all images, but left the table view untouched.

Upvotes: 2

Chiakie
Chiakie

Reputation: 271

If you want to remove uiimageviews in scrollview.subviews, and you also want to keep the vertical and horizontal indicators. You can set a special "tag" to identify views and exclude vertical and horizontal indicators whose tags are 0 by default.

Upvotes: 1

Ricardo de Cillo
Ricardo de Cillo

Reputation: 1164

I think you just have to be careful and not to delete the scroll indicator bars.

The code given by Adam Ko is short and elegant but it may delete the horizontal and vertical scroll indicators.

I usually do

for (UIView *v in scrollView.subviews) {
  if (![v isKindOfClass:[UIImageView class]]) {
    [v removeFromSuperview];
  }
}

Suposing you don't have UIImageView's added to the scroll manually.

Upvotes: 35

Related Questions