Check if a subview is in a view using Swift

Suragch picture Suragch · Jun 19, 2015 · Viewed 31.6k times · Source

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.

Answer

Suragch picture Suragch · Jun 19, 2015

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.