I have added my subview using
self.view.addSubview(noticeSubView)
At some point I need to check if that subview exists before proceeding with some other actions etc. I found the following while searching but not sure if it is how it is done and also how to implement.
BOOL doesContain = [self.view.subviews containsObject:pageShadowView];
I appreciate any help, thanks.
If you need a quick way to get hold of a view inside a complicated view hierarchy, you're looking for viewWithTag() – give it the tag to find and a view to search from, and this method will search all subviews, and all sub-subviews, and so on, until it finds a view with the matching tag number.
Rather than asking if a subview exists in your view, you are better off asking if the subview (in your case noticeSubView) has a parent that is your view.
So in your example you would check later for:
if ( noticeSubView.superview === self.view ) {
...
}
The triple "===" is making sure that the superview object is the same object as self.view, instead of trying to call isEqual() on the view.
Another approach people have used in the past is to set an integer tag on a subview, like so:
noticeSubView.tag = 4
The default is zero so anything nonzero will be unique.
Then you can check to see if a superview contains a specific view by tag:
if ( self.view?.viewWithTag(4) != nil )
...
}
If you take that approach, you should probably create an enum for the integer value so it's clearer what you are looking for.
Note: There's a "?" after self.view
because a view controller will not have a view defined until after viewDidLoad
, the "?" makes sure the call will not occur if self.view
returns .None
If noticeSubView
is a custom class (let's call it NoticeSubView
), then 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 to the view and search for it.
noticeSubView.tag = 99
//...
for view in self.view.subviews {
if view.tag == 99 {
// Subview exists
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With