Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView: How to find out if a view is already exists?

Tags:

I was wondering how to find out if a subview (in my case pageShadowView) has already been added to my view.

I've come up with this, but it doesn't really work:

if ([pageShadowView isKindOfClass:[self.view class]]) {         [self.view addSubview:pageShadowView];     } 

Also, I'm still confused about the self.-thing. I know that this has to do with making clear that we are talking about the view of the current ViewController ... but do I really need it if there (1) are no other ViewControllers or (2) if it doesn't really matter because if I ever wanted to refer to another viewController, I'd make sure to call it?

I'm sorry if this is all very basic, but I'd be very grateful for your comments.

like image 707
n.evermind Avatar asked Mar 31 '11 16:03

n.evermind


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.

What is the difference between UIView and UIViewController?

They are separate classes: UIView is a class that represents the screen of the device of everything that is visible to the viewer, while UIViewController is a class that controls an instance of UIView, and handles all of the logic and code behind that view.


2 Answers

Here:

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

And yes, you need this self. There is no explicit ivar "view" on UIViewController. The self.view statement is actually a call on method [self view] which is a getter for UIViewController's view.

like image 175
Bartosz Ciechanowski Avatar answered Oct 04 '22 23:10

Bartosz Ciechanowski


Give it a unique tag: view.tag = UNIQUE_TAG, then check the container view for existence:

BOOL alreadyAdded = [containerView viewWithTag:UNIQUE_TAG] != nil; 
like image 35
coneybeare Avatar answered Oct 05 '22 00:10

coneybeare