Check if a subview is in a view using Swift Check if a subview is in a view using Swift ios ios

Check if a subview is in a view using Swift


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


for view in self.view.subviews {    if let subView = view as? YourNameView {        subView.removeFromSuperview()        break    }}


matomo