Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only user-added subviews from my UIView

I'm trying to remove all the subviews that I've added to my view, so I've implemented a loop to iterate over the subviews with the following:

for subview in view.subviews {
    println(subview)
    //subview.removeFromSuperview()
}

I tested this by adding a UILabel to my view and then ran this code. The output contained my UILabel but also a _UILayoutGuide. So, my question is how can I determine if a subview is one that I added or one that the system added?

like image 589
Epsilon Avatar asked Dec 01 '14 21:12

Epsilon


2 Answers

If you just want to prevent the loop from removing the _UILayoutGuide (which is of class UILayoutSupport), try this:

for subview in self.view.subviews {
    if !(subview is UILayoutSupport) {
        print(subview)
        subview.removeFromSuperview()
     }
}

And generally speaking, if you'd like to prevent the removal of views other than the _UILayoutGuide and if you know the specific types of subviews you'd like to remove from your UIView, you can limit the subviews you remove to those types, ex:

for subview in view.subviews {
    if subview is ULabel {
        println(subview)
        subview.removeFromSuperview()
    }
}
like image 120
Lyndsey Scott Avatar answered Oct 20 '22 23:10

Lyndsey Scott


One option is to give all the views you add a specific tag. Then only remove them if they have that tag.

userCreatedView.tag = 100;

...

for subview in view.subviews {
    if (subview.tag == 100) {
        subview.removeFromSuperview()
    }
}

You could also keep an Array of all the subviews that the user has added then check to see if that subview is in your userAddedViewsArray

Or you could create a subclass of UIView for your user added views and then only remove the subviews that are that class

like image 33
Joel Bell Avatar answered Oct 20 '22 23:10

Joel Bell