Check if a subview is in a view using Swift
Asked Answered
M

4

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.

Microbe answered 19/6, 2015 at 11:45 Comment(2)
possible duplicate of Check if a subview is in a view (importantly, that question already has a Swift answer...)Placable
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?Involucel
M
90

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.

Microbe answered 19/6, 2015 at 11:45 Comment(0)
S
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
        }
    }
}
Shawnshawna answered 24/12, 2016 at 19:0 Comment(1)
I'm not sure if it's cleaner or not, but it looks like a good alternate method.Microbe
H
11
for view in self.view.subviews {
    if let subView = view as? YourNameView {
        subView.removeFromSuperview()
        break
    }
}
Helton answered 17/5, 2019 at 3:41 Comment(1)
this actually removes the first view of that type of views, but not that you probably wantUnsnap
M
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.
}
Menell answered 17/5, 2019 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.