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.
Asked
Active
Viewed 4.8k times
36
-
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
-
1In 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 Answers
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
-
3I'm not sure if it's cleaner or not, but it looks like a good alternate method. – Suragch Dec 25 '16 at 04:30
11
for view in self.view.subviews {
if let subView = view as? YourNameView {
subView.removeFromSuperview()
break
}
}

Giang
- 3,553
- 30
- 28
-
this actually removes the first view of that type of views, but not that you probably want – Zaporozhchenko Oleksandr Feb 04 '21 at 09:52
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