Check if a subview is in a view using Swift
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
}
}
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.