Check if subview exists in swift 1.2

I added my subview using

self.view.addSubview(noticeSubView) 

At some point I need to check if this is a subtask before proceeding with other actions, etc. I found the following when searching, but not sure if this is how it is done, nor how to implement it.

 BOOL doesContain = [self.view.subviews containsObject:pageShadowView]; 

I appreciate any help, thanks.

+5
source share
2 answers

Instead of asking if a subzone exists in your view, you better ask if the sub-element (in your case noticeSubView) has a parent element that is your view.

So, in your example, you would clarify later:

 if ( noticeSubView.superview === self.view ) { ... } 

The triple "===" ensures that the superiew object is the same object as self.view, rather than trying to call isEqual () on the view.

Another approach that people have used in the past is to set an integer tag on a subview, for example:

 noticeSubView.tag = 4 

The default value is zero, so any nonzero value will be unique.

Then you can check if the supervisor contains a specific view by tag:

 if ( self.view?.viewWithTag(4) != nil ) ... } 

If you take this approach, you should probably create an enumeration for an integer value so that it clears what you are looking for.

Note: is there ?? after self.view , because the view controller will not have the view defined after viewDidLoad , "?" make sure the call does not happen if self.view returns .None

+19
source

If noticeSubView is a custom class (call it noticeSubView ), you can find it like this:

 for view in self.view.subviews { if let noticeSubView = view as? NoticeSubView { // Subview exists } } 

Or you can assign a tag for the presentation and search.

 noticeSubView.tag = 99 //... for view in self.view.subviews { if view.tag == 99 { // Subview exists } } 
+2
source

All Articles