soleil
soleil

Reputation: 13083

iOS - presentViewController with transparency

I would like to present a view controller full screen semi-transparently so that I still see the view underneath it. The following code presents the new view controller, but it replaces the current one. What is the best way to keep the original view controller visible? The view of the new view controller will have a semi-transparent black background.

NewViewController* newVC = [[NSClassFromString(@"NewViewController") alloc] initWithNibName:deviceNib bundle:nil];
newVC.modalPresentationStyle = UIModalPresentationFullScreen;
newVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;


[self presentViewController:newVC animated:YES completion:NULL];

Upvotes: 5

Views: 7827

Answers (2)

nalexn
nalexn

Reputation: 10791

You can present semi-transparent modal controller in the following way:

NewViewController* newVC = [[NSClassFromString(@"NewViewController") alloc] initWithNibName:deviceNib bundle:nil];

self.modalPresentationStyle = UIModalPresentationCurrentContext;
newVC.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;

[self presentViewController:newVC animated:YES completion:NULL];

Notice here that you have to set the constant UIModalPresentationCurrentContext to self.modalPresentationStyle, not to newVC.modalPresentationStyle

Furthermore, when you use UIModalTransitionStyleCrossDissolve the alpha of the newVC.view will be overridden during the transition, so if you want semi-transparent background you'll need to keep newVC.view's backgroundColor clear and just add another UIView as it's subview with semi-transparent backgroundColor

Upvotes: 2

CSmith
CSmith

Reputation: 13458

Present a semi-transparent View, not a view controller.

mySemiTransparentView.alpha = 0.0f;
[self.view addSubview:mySemiTransparentView];

mySemiTransparentView is your full-screen view. You can animate it into place:

[UIView beginAnimations:@"fadeIn" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:0.4f];
mySemiTransparentView.alpha = 0.5f;
[UIView commitAnimations];

Upvotes: 6

Related Questions