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.
If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.
The superview is the immediate ancestor of the current view. The value of this property is nil when the view is not installed in a view hierarchy. To set the value of this property, use the addSubview(_:) method to embed the current view inside another view.
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.
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 } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With