iOS - Semi-transparent modal view controller

2019-02-02 05:23发布

I want to present a view controller with a slightly transparent background modally over the current view, such that the first view is slightly visible under the modal view.

I set the alpha value of the modal view controller and set the modalPresentationStyle to UIModalPresentationCurrentContext, as suggested in another post.

The result is that the view background is transparent when animating up, but when view controller is in place it changes to opaque black. It goes back to being transparent while animating the dismissal.

How can I get it to be transparent when active ?

I have tested in iOS 6 and 7. The code I am using follows:

MyModalViewController *viewController = [[MyModalViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[navController setNavigationBarHidden:YES];
self.navigationController.modalPresentationStyle = UIModalPresentationCurrentContext;
[self.navigationController presentViewController:navController animated:YES completion:NULL];

8条回答
乱世女痞
2楼-- · 2019-02-02 05:50

If you are targeting ios 8 and above you can set the modal presentation style to "over current context" and you are done. If ios 7 and below, you would have to create a custom transition style so that the presenting screen doesn't go blank after transition. That is rather complicated.

The solution I present offers a lot of flexibility: make a screenshot before showing the modal dialog and set that as the background image for the application window. By default, that background is black (that is what you see when the back view controller dissapears). Change the background to the screenshot of the app. Make the screenshot in the viewWillAppear or viewDidLoad method of your transparent view. This works even with push segues, not only modal dialogs, but you should avoid animations. In general, avoid animations which affect the position of the background view because those will make it seem like it snaps back into place when transition finishes. It is a good idea to reset the background to its previous black image on viewDidDissapear to avoid unwanted effects.

You can maintain a stack of such background images and you can do multiple "transparent" push seques. Or have some complex/deep menu which appears on top of some main screen. For these many reasons I think this solution is better than rolling your own transitioning code. It is more flexible and easier to implement, and you don't have to deal with the animations yourself.

查看更多
相关推荐>>
3楼-- · 2019-02-02 05:57

Why don't you try setting this in AppDelegate

self.window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;

then changing the alpha on the view being presented

查看更多
登录 后发表回答