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

36,174

Solution 1

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.

Solution 2

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

BOOL alreadyAdded = [containerView viewWithTag:UNIQUE_TAG] != nil;

Solution 3

you can find a sub view like this

for(UIView *view in self.view.subviews)
{
    if([view isKindOfClass:[UIView class]])
    {
        //here do your work
    }
}

Solution 4

There's one more way to find, in Swift: isDescendant(of view: UIView) -> Bool or in Obj-C: - (BOOL)isDescendantOfView:(UIView *)view

Swift:

    if myView.isDescendant(of: self.view) {
        //myView is subview of self.view, remove it.
        myView.removeFromSuperview()
    } else {
        //myView is not subview of self.view, add it.
        self.view.addSubview(myView)
    }

Obj-C:

if([myView isDescendantOfView:self.view]) {   
    //myView is subview of self.view, remove it.
    [myView removeFromSuperView];
} else {
    //myView is not subview of self.view, add it.
    [self.view addSubView:myView];
}

Solution 5

SWIFT VERSION:

let doesContain = self.view?.subviews.contains(pageShadowView)
Share:
36,174
n.evermind
Author by

n.evermind

I speak: Copy-and-paste, Basic, Objective-C, Python, Django and have recently learned how to use the very retro but stylish terminal. Otherwise: Creator of digital-analog-but-stunningly beautiful notebooks in love with beautiful UIs

Updated on December 11, 2020

Comments

  • n.evermind
    n.evermind over 3 years

    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.