Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if subview exists in swift 1.2

Tags:

swift

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.

like image 690
john tully Avatar asked May 26 '15 01:05

john tully


People also ask

How do you check if a view contains a Subview?

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.


2 Answers

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

like image 53
Kendall Helmstetter Gelner Avatar answered Oct 22 '22 21:10

Kendall Helmstetter Gelner


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
    }
}
like image 22
keithbhunter Avatar answered Oct 22 '22 22:10

keithbhunter