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.
Check if a subview is in a view using Swift
possible duplicate of Check if a subview is in a view (importantly, that question already has a Swift answer...) –
Placable
In response to nhgrif's comment, the answer you linked to (an Obj-C question) was edited (by YOU) the same day you posted the comment. Did it have Swift at 11:45am when this question was posted and was it an adequate answer? If so, why'd you update it? –
Involucel
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
}
}
}
I'm not sure if it's cleaner or not, but it looks like a good alternate method. –
Microbe
for view in self.view.subviews {
if let subView = view as? YourNameView {
subView.removeFromSuperview()
break
}
}
this actually removes the first view of that type of views, but not that you probably want –
Unsnap
Here we used two different views. Parent view is the view in which we are searching for descendant view and check wether added to parent view or not.
if parentView.subviews.contains(descendantView) {
// descendant view added to the parent view.
}else{
// descendant view not added to the parent view.
}
© 2022 - 2024 — McMap. All rights reserved.