iosswiftuiviewsubviews

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?


Solution

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