john tully
john tully

Reputation: 309

Check if subview exists in swift 1.2

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.

Upvotes: 5

Views: 6096

Answers (3)

Muhammad Ahmad
Muhammad Ahmad

Reputation: 398

best and easy way to find that your view is exist or not , there are many way like you check a view is contain or not in super view or just view some time this method is failed because if the Uiview is already remove then error occur, so code is here : here errorView is my UiView

 errorView.tag = 333

 if ( self.view?.viewWithTag(333) != nil ){
    print("contain")
 }

 else {
    print("not contain")
 }

Upvotes: -1

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

Upvotes: 22

keithbhunter
keithbhunter

Reputation: 12334

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
    }
}

Upvotes: 2

Related Questions