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?
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()
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With