Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a subview is in a view using Swift

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.

like image 517
Suragch Avatar asked Jun 19 '15 11:06

Suragch


People also ask

How do you check if a view contains a Subview?

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.

What is super view in Swift?

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.


2 Answers

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.

like image 72
Suragch Avatar answered Oct 20 '22 16:10

Suragch


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         }     } } 
like image 43
Ryan Cocuzzo Avatar answered Oct 20 '22 15:10

Ryan Cocuzzo