Remove all the subviews from a UIScrollView?

Moshe picture Moshe · Nov 5, 2010 · Viewed 27k times · Source

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

Answer

koo picture koo · Nov 5, 2010

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()
}