Use of UIWindow to prevent extra addSubview: call in client code

94 views Asked by At

I'm building a UIView subclass for pushing views in and out of the screen (think wizard/tutorial). Let's call it PageView.

To use it you add the views you want to animate in the desired order and call a "next" method to perform each transition.

.....

PageView *pageView = [PageView new];

_view1 = [[[NSBundle mainBundle] loadNibNamed:@"View1" owner:self options:nil] objectAtIndex:0];
_view1.frame = self.view.bounds;
_view2 = [[[NSBundle mainBundle] loadNibNamed:@"View2" owner:self options:nil] objectAtIndex:0];
_view2.frame = self.view.bounds;

[_pageView addView:_view1];
[_pageView addView:_view2];

.....

//at some point later
[pageView next];

Essentially a "UIPageViewController" that uses UIViews instead of UIViewControllers.

enter image description here

It uses CATransition under the hood and works very well.

My question is related to the API provided to client code.

For the PageView object to appear on screen I can:

1) "implicitly" ask the person using the class to add it using addSubview:

[self.view addSubview:_pageView];

This has the obvious disadvantage of one extra call. It is also easy to forget or use at the wrong place/time.

2) Pass "self" as a parameter during initialization and let PageView handle the "addSubview" part internally.

This approach is slightly better in my opinion, but introduces an extra parameter during initialization.

PageView *pageView = [[PageView alloc] initWithContainerView:self]; 

.....

//then somewhere inside PageView

[containerView addSubview: self];

3) I can use UIWindow to do something like this:

//inside PageView

UIWindow *mainWindow = [[[UIApplication sharedApplication] windows] firstObject];
[mainWindow addSubview:self];
//mainWindow.windowLevel = UIWindowLevelAlert;

Magic! No extra calls, no extra parameters. It just works.

My questions: has anyone experienced problems and/or unexpected behavior when using UIWindow to "present" views on top of other views?

Also, is it "safe" to use UIWindowLevelAlert for this?

It works without it and Apple says it is not needed to bring your views on "top" but at the same time the documentation clearly states that any view on that layer will always obscure any views on a level below (UIWindowLevelNormal aka default level). So why not use it?

0

There are 0 answers