36

How do I test if a subview has already been added to a parent view? If it hasn't been added, I want to add it. Otherwise, I want to remove it.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • possible duplicate of [Check if a subview is in a view](http://stackoverflow.com/questions/7421298/check-if-a-subview-is-in-a-view) (importantly, that question already has a Swift answer...) – nhgrif Jun 19 '15 at 12:21
  • 1
    In response to nhgrif's comment, the answer you linked to (an Obj-C question) was edited (by YOU) the same day you posted the comment. Did it have Swift at 11:45am when this question was posted and was it an adequate answer? If so, why'd you update it? – Dave G Feb 18 '17 at 17:24

4 Answers4

88

You can use the UIView method isDescendantOfView:

if mySubview.isDescendant(of: someParentView) {
    mySubview.removeFromSuperview()
} else {
    someParentView.addSubview(mySubview)
}

You may also need to surround everything with if mySubview != nil depending on your implementation.

Zaporozhchenko Oleksandr
  • 4,660
  • 3
  • 26
  • 48
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
26

This is a much cleaner way to do it:

if myView != nil { // Make sure the view exists

        if self.view.subviews.contains(myView) {
            self.myView.removeFromSuperview() // Remove it
        } else {
           // Do Nothing
        }
    }
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
Ryan Cocuzzo
  • 3,109
  • 7
  • 35
  • 64
11
for view in self.view.subviews {
    if let subView = view as? YourNameView {
        subView.removeFromSuperview()
        break
    }
}
Giang
  • 3,553
  • 30
  • 28
7

Here we used two different views. Parent view is the view in which we are searching for descendant view and check wether added to parent view or not.

if parentView.subviews.contains(descendantView) {
   // descendant view added to the parent view.
  }else{
   // descendant view not added to the parent view.
}
shubham
  • 611
  • 7
  • 16