Check if there is a preview in the view using Swift

How to check if a preview has been added to the parent view? If it has not been added, I want to add it. Otherwise, I want to delete it.

+11
source share
4 answers

You can use the UIView isDescendantOfView method:

 if mySubview.isDescendantOfView(someParentView) { someParentView.mySubview.removeFromSuperview() } else { someParentView.addSubview(mySubview) } 

You may also need to surround everything with if mySubview != nil depending on your implementation.

+36
source

This is a much cleaner way to do this:

 if myView != nil { // Make sure the view exists if self.view.subviews.contains(myView) { self.myView.removeFromSuperview() // Remove it } else { // Do Nothing } } } 
+12
source
 for view in self.view.subviews { if let subView = view as? YourNameView { subView.removeFromSuperview() break } } 
0
source

Here we used two different views. A parent view is a view in which we look for a child and check if the parent view is added to the parent or not.

 if parentView.subviews.contains(descendantView) { // descendant view added to the parent view. }else{ // descendant view not added to the parent view. } 
0
source

Source: https://habr.com/ru/post/989395/


All Articles