trouble with displaying another UIWindow

2019-04-12 13:41发布

问题:

I'm writing an iPad app, and I'm trying to display a second UIWindow on top of the main window in my app. The main thing I'm trying to do is create a log in window (how to present a login, with UISplitViewController?), and it seems that creating a second window here might be a good option.

I've made a very simple app to try this out. When the user hits a button, then I'm trying to show the second window. Here's the code:

- (IBAction)showOtherWindow:(id)sender {
    UIWindow* otherWindow = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    otherWindow.hidden = NO;
    otherWindow.clipsToBounds = YES;
    otherWindow.windowLevel = UIWindowLevelStatusBar;
    otherWindow.backgroundColor = [UIColor redColor];
    [otherWindow makeKeyAndVisible];
}

I'm expecting to see a big red screen here, but that doesn't happen - nothing changes. Ultimately, I'd like to have a smaller window floating on top. But right now I'd just like to see a window at all.

回答1:

If you're in ARC code your window is getting deallocated immediately after showOtherWindow: returns. Try assigning otherWindow to an ivar in a persistent object.



回答2:

Assign the window's pointer to a __strong instance variable (ivar) or a strong property. Set the ivar or property to nil after you dismiss the window.



回答3:

In iOS you have one window that fills all the screen. To do what you want you may create a UIViewController/UIView and open it in modal mode.

From your main View Controller you may do something like

UILoginViewController *login = [[UILoginViewController alloc] init]; 
login.modalPresentationStyle = UIModalPresentationFormSheet; // or whatever you prefer

login.completionWithItemsHandler = hdl;

[self presentViewController:login animated:YES completion:nil];