Check if a subview is in a view using Swift

50.1k views Asked by At

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.

4

There are 4 answers

0
Suragch On BEST ANSWER

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.

1
Ryan Cocuzzo On

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
        }
    }
}
1
Giang On
for view in self.view.subviews {
    if let subView = view as? YourNameView {
        subView.removeFromSuperview()
        break
    }
}
0
shubham On

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.
}