80

I am displaying a modal view with

[self presentModalViewController:controller animated:YES];

When the view moves up the screen it is transparent as per the setting in the xib file it is created from, but once it fills the screen it goes opaque.

Is there anyway of keeping the view transparent?

I suspect that the view it is being placed over is not being rendered rather then that the modal view is becoming opaque.

3
  • 1
    This question is now pretty old. When looking for answers look for one that applies to the version of iOS that you use. Sep 23, 2014 at 16:58
  • This stackoverflow.com/q/27598846/1603234 make me smile, now your turn :)
    – Hemang
    Dec 22, 2014 at 8:18
  • you can use viewcontroller.modalPresentationStyle = .FormSheet
    – Gerald
    Mar 23, 2016 at 4:55

21 Answers 21

85

After iOS 3.2 there is a method to do this without any “tricks” – see the documentation for the modalPresentationStyle property. You have a rootViewController which will present the viewController. So here's the code to success:

viewController.view.backgroundColor = [UIColor clearColor];
rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
[rootViewController presentModalViewController:viewController animated:YES];

With this method the viewController's background will be transparent and the underlying rootViewController will be visible. Please note that this only seems to work on the iPad, see comments below.

18
  • 1
    Hi.. +1 from my side bcoz it works fine in iOS 4 and iPad. but how it will work in iPhone 3.0. Thanks May 3, 2011 at 8:38
  • 3
    It's not working for me (iOS 5.0), can someone show some code?
    – Daniel
    Jan 18, 2012 at 17:19
  • 6
    This does not appear to work on iPhone/iPod, only iPad (see documentation linked in the answer). @simpleBob: maybe this is why it's not working for you?
    – Mac
    Apr 20, 2012 at 2:07
  • 1
    FYI: I have asked the same question in this post: stackoverflow.com/questions/14419395/…
    – user843337
    Jan 19, 2013 at 22:09
  • 1
    I tested on iOS 8, and I have to use Over Current Context as presentation style.
    – haxpor
    Sep 7, 2015 at 2:20
63

Your view is still transparent, but once your modal controller is at the top of the stack, the view behind it is hidden (as is the case with any top-most view controller). The solution is to manually animate a view yourself; then the behind-viewController won't be hidden (since you won't have 'left' it).

3
  • Thanks, that confirms what I suspected. Feb 26, 2009 at 0:26
  • 1
    I've filed a bug report with Apple about this issue. Open Radar: openradar.appspot.com/radar?id=1062402
    – theory
    Jan 29, 2011 at 22:05
  • 4
    Problem with this is the presented view can't have its own autorotation settings.
    – Shizam
    Sep 15, 2013 at 1:52
48

What I needed to get this to work:

self.window.rootViewController.modalPresentationStyle = UIModalPresentationCurrentContext;
6
  • 1
    it simple works , thanks i just kept my code on - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method and voila Jan 24, 2013 at 10:54
  • 2
    You can also just set the modalPresentationStyle on the presenting view controller (instead of on the window's rootViewController). Jun 19, 2013 at 10:24
  • Thanks!! even works when you do, [self performSegueWithIdentifier:@"open" sender:self];
    – DogCoffee
    Oct 18, 2013 at 11:02
  • You can always animate the view by hand in viewdidload of the modal.
    – Jacob K
    Nov 7, 2013 at 11:46
  • 2
    Note that, as Mr. T said below, the modalPresentationStyle has to be set on the view controller that currently has the full screen.
    – jessepinho
    Nov 8, 2013 at 9:48
24

For those who want to see some code, here's what I added to my transparent view's controller:

// Add this view to superview, and slide it in from the bottom
- (void)presentWithSuperview:(UIView *)superview {
    // Set initial location at bottom of superview
    CGRect frame = self.view.frame;
    frame.origin = CGPointMake(0.0, superview.bounds.size.height);
    self.view.frame = frame;
    [superview addSubview:self.view];            

    // Animate to new location
    [UIView beginAnimations:@"presentWithSuperview" context:nil];
    frame.origin = CGPointZero;
    self.view.frame = frame;
    [UIView commitAnimations];
}

// Method called when removeFromSuperviewWithAnimation's animation completes
- (void)animationDidStop:(NSString *)animationID
                finished:(NSNumber *)finished
                 context:(void *)context {
    if ([animationID isEqualToString:@"removeFromSuperviewWithAnimation"]) {
        [self.view removeFromSuperview];
    }
}

// Slide this view to bottom of superview, then remove from superview
- (void)removeFromSuperviewWithAnimation {
    [UIView beginAnimations:@"removeFromSuperviewWithAnimation" context:nil];

    // Set delegate and selector to remove from superview when animation completes
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(animationDidStop:finished:context:)];

    // Move this view to bottom of superview
    CGRect frame = self.view.frame;
    frame.origin = CGPointMake(0.0, self.view.superview.bounds.size.height);
    self.view.frame = frame;

    [UIView commitAnimations];    
}
4
  • The only problem I have with this solution is memory management. For example: TestViewController *testView = [[TestViewController alloc]initWithNibName:@"TestView" bundle:nil]; [testView presentWithSuperview:self.navigationController.view]; Will work fine, however if you attempt to release or autorelease the View, any calls to methods within that view, will result in bad access exceptions Apr 5, 2010 at 15:07
  • Are you sure? I think the view will be retained by [superview addSubview:], so you should be able to release it. Apr 5, 2010 at 17:36
  • If you call presentWithSuperview then release testView it crashes. It also displays displays "under" any NavigationController toolbars etc. May 14, 2010 at 1:31
  • This has worked fine for me for a long time, but it no longer works in landscape mode. Anyone have this same issue? Mar 19, 2015 at 15:10
19

The Apple-approved way to do this in iOS 8 is to set the modalPresentationStyle to 'UIModalPresentationOverCurrentContext'.

From the UIViewController documentation:

UIModalPresentationOverCurrentContext

A presentation style where the content is displayed over only the parent view controller’s content. The views beneath the presented content are not removed from the view hierarchy when the presentation finishes. So if the presented view controller does not fill the screen with opaque content, the underlying content shows through.

When presenting a view controller in a popover, this presentation style is supported only if the transition style is UIModalTransitionStyleCoverVertical. Attempting to use a different transition style triggers an exception. However, you may use other transition styles (except the partial curl transition) if the parent view controller is not in a popover.

Available in iOS 8.0 and later.

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIViewController_Class/

The 'View Controller Advancements in iOS 8' video from WWDC 2014 goes into this in some detail.

Be sure to give your presented view controller a clear background color (otherwise, it will still appear opaque).

2
  • it gives me a black screen on iOS8 and iOS9
    – Amit Hooda
    Nov 17, 2015 at 6:55
  • Actually it works if you set your view controller's view a background color with an alpha value below 1
    – Pierre
    Jul 6, 2017 at 8:40
16

There is another option: before showing the modal controller, capture a screenshot of the whole window. Insert the captured image into an UIImageView and add the image view to the controller's view you're about to show. Then send to back. Insert another view above the image view (background black, alpha 0.7). Show your modal controller and it looks like it was transparent. Just tried it on iPhone 4 running iOS 4.3.1. Like charm.

3
  • good one, i implement this it was great for me.add my code which follow this concept.
    – Ishu
    Jul 15, 2011 at 7:23
  • Nobody said it's going to be easy! :-)
    – Krumelur
    Aug 11, 2011 at 13:30
  • How would you support device rotation with this approach?
    – Kyle Clegg
    Dec 19, 2012 at 23:07
10

this is quite old, but i solved the same problem as follows: Since i need to present a navigation controller in iPhone, adding a subview wasn't a viable solution.

So what i did:

1) Before presenting the view controller, take a screenshot of your current screen:

UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * backgroundImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

2) Create the view controller you want to present, and add the background as a subview, sending it to back.

UIViewController * presentingVC = [UIViewController new];
UIImageView * backgroundImageOfPreviousScreen = [[UIImageView alloc] initWithImage:backgroundImage];
[presentingVC.view addSubview:backgroundImageOfPreviousScreen];
[presentingVC.view sendSubviewToBack:backgroundImageOfPreviousScreen];

3) Present your view controller, but before that in the new view controller, add a transparent view in the viewDidLoad (i used ILTranslucentView)

-(void)viewDidLoad
{
    [super viewDidLoad];
    ILTranslucentView * translucentView = [[ILTranslucentView alloc] initWithFrame:self.view.frame];
    [self.view addSubview:translucentView];
    [self.view sendSubviewToBack:translucentView];
}

And that's all!

3
  • Awesome. All worked well beside the translucent view which caused the screen shot disappearance. Apr 8, 2014 at 13:26
  • This is a great solution! It is better for keeping the controller code for the popup separate from the parent view controller.
    – 1kmonkies
    May 8, 2014 at 4:09
  • For me worked but setting background had to be in viewWillAppear Jun 16, 2014 at 15:30
5

I wrote down my findings about this in a different question, but the gist of it is that you have to call modalPresentationStyle = UIModalPresentationCurrentContext on whatever owns the full screen at the moment. Most of the time, it's whatever is the [UIApplication sharedApplication].delegate.window's rootViewController. It could also be a new UIViewController that was presented with modalPresentationStyle = UIModalPresentationFullScreen.

Please read my other much more detailed post if you're wondering how I specifically solved this problem. Good luck!

5

This appears to be broken in IOS 8, I am using a navigation controller and the context that is being displayed is the Navigation menus context which in our case is a sliding Menu controller.

We are using pod 'TWTSideMenuViewController', '0.3' have not checked to see if this is an issue with the library yet or the method described above.

5

This worked to me in iOS 8-9:

1- Set your view controller's background with an alpha

2- add this code:

TranslucentViewController *tvc = [[TranslucentViewController alloc] init];
self.providesPresentationContextTransitionStyle = YES;
self.definesPresentationContext = YES;
[tvc setModalPresentationStyle:UIModalPresentationOverCurrentContext];

[self.navigationController presentViewController:tvc animated:YES completion:nil];
4

I know this is pretty old question. I was stuck on this issue and I was able to get a lead from this thread. So putting here how I got it worked :) . I am using storyboard and I have segue to the ViewController which is to be presented. The view controller have a transparent background colour. Now in the Attributes inspector of the segue I set the presentation to "Over current context".And it worked for me. I am developing for iPhone.

Attributes Inspector of the segue

1
  • thanks, also works by set UIModalPresentationStyle.OverCurrentContext programmatically
    – guoleii
    Jun 1, 2016 at 3:30
3

I've created open soruce library MZFormSheetController to present modal form sheet on additional UIWindow. You can use it to present transparency modal view controller, even adjust the size of the presented view controller.

1
  • Can you explain how to use it? Because when I try to invoke the code it cause SIGABRT. Nov 4, 2014 at 11:39
3

In my condition i am having view on same viewController. So make a new view controller for holding UIView. Make that view transparent by setting it's alpha property. Then on a button click i wrote this code. It looks good.

UIGraphicsBeginImageContext(objAppDelegate.window.frame.size);
    [objAppDelegate.window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();



    UIViewController *controllerForBlackTransparentView=[[[UIViewController alloc] init] autorelease];
    [controllerForBlackTransparentView setView:viewForProfanity];

    UIImageView *imageForBackgroundView=[[UIImageView alloc] initWithFrame:CGRectMake(0, -20, 320, 480)];
    [imageForBackgroundView setImage:viewImage];

    [viewForProfanity insertSubview:imageForBackgroundView atIndex:0];

    [self.navigationController presentModalViewController:controllerForBlackTransparentView animated:YES];

And it shows what i want. hope it help some one.

0
2

Here's a category I've created that will solve the problem.

    //
    //  UIViewController+Alerts.h
    //

    #import <UIKit/UIKit.h>

    @interface UIViewController (Alerts)

    - (void)presentAlertViewController:(UIViewController *)alertViewController animated:(BOOL)animated;
    - (void)dismissAlertViewControllerAnimated:(BOOL)animated;

    @end


    //
    //  UIViewController+Alerts.m
    //

    #import "UIViewController+Alerts.h"

    @implementation UIViewController (Alerts)

    - (void)presentAlertViewController:(UIViewController *)alertViewController animated:(BOOL)animated
    {
            // Setup frame of alert view we're about to display to just off the bottom of the view
            [alertViewController.view setFrame:CGRectMake(0, self.view.frame.size.height, alertViewController.view.frame.size.width, alertViewController.view.frame.size.height)];

            // Tag this view so we can find it again later to dismiss
            alertViewController.view.tag = 253;

            // Add new view to our view stack
            [self.view addSubview:alertViewController.view];

            // animate into position
            [UIView animateWithDuration:(animated ? 0.5 : 0.0) animations:^{
                    [alertViewController.view setFrame:CGRectMake(0, (self.view.frame.size.height - alertViewController.view.frame.size.height) / 2, alertViewController.view.frame.size.width, alertViewController.view.frame.size.height)];
            }];      
    }

    - (void)dismissAlertViewControllerAnimated:(BOOL)animated
    {
            UIView *alertView = nil;

            // find our tagged view
            for (UIView *tempView in self.view.subviews)
            {
                    if (tempView.tag == 253)
                    {
                            alertView = tempView;
                            break;
                    }
            }

            if (alertView)
            {
                    // clear tag
                    alertView.tag = 0;

                    // animate out of position
                    [UIView animateWithDuration:(animated ? 0.5 : 0.0) animations:^{
                            [alertView setFrame:CGRectMake(0, self.view.frame.size.height, alertView.frame.size.width, alertView.frame.size.height)];
                    }];      
            }
    }

    @end
4
  • 4
    FYI, no need to loop through the subviews on your own in the dismiss method. The framework will do it for you with [self.view viewWithTag:253];
    – SteveB
    Jun 26, 2012 at 20:28
  • Dave Wood's category on this example displays your view as-is. So you must also set your background of your xib's view's Alpha setting to lower than 1 to get the translucent effect. Dec 31, 2012 at 21:25
  • This category has a problem when presenting over a scrollable view such as a table view: Scrolling works. That's bad. The user can scroll the presented view off-screen. The underlying presenting view's contents come onto the screen. Dec 31, 2012 at 21:27
  • I've since updated this category. You can get the code here: gist.github.com/4423365. I use it over table views and collection views without the scrolling problem you describe.
    – Dave Wood
    Dec 31, 2012 at 22:29
2

After a lot of research looks like this will solve our issue and serve our purpose.

create a segue from source VC to destination VC with an identifier.

for example "goToDestinationViewController" okay to makes lives easy let's consider the current view controller i.e, the one you want behind your transparent view as source and the destination as destination

Now in source VC in viewDidLoad: or view

performSegueWithIdentifier("goToDestinationViewController", sender: nil)

good we are half way through. Now go to your storyboard. Click on the segue. which should look like this: segue

change the options to what are shown.

Now comes the real solution.

in your destination view controller's viewDidLoad add this code.

self.modalPresentationStyle = .Custom

.........................................................................THAT EASY..................................................................

2
  • 1
    Setting self.modalPresentationStyle = .custom works for me in modally presenting an actual view controller with a transparent background in Swift 3, Xcode 8. The only issue is that if the presenting view controller is embedded in a tab bar controller, the tab bar shows up in front of the transparent background view.
    – mtso
    Aug 29, 2016 at 5:52
  • So—if a tab bar is in use—the presenting view controller's tabBarController.tabBar.isHidden should then be set to true.
    – mtso
    Aug 29, 2016 at 6:07
1

Alternate way is to use a "container view". Just make alpha below 1 and embed with seque. XCode 5, target iOS7.

can't show image, not enough reputation)))

Container view available from iOS6.

1

This code works fine on iPhone under iOS6 and iOS7:

presentedVC.view.backgroundColor = YOUR_COLOR; // can be with 'alpha'
presentingVC.modalPresentationStyle = UIModalPresentationCurrentContext;
[presentingVC presentViewController:presentedVC animated:YES completion:NULL];

But along this way you loose 'slide-from-the-bottom' animation.

3
  • This doesn't work for me on iPhone. The underneath view still disappears. I believe modalPresentationStyle only applies to iPad.
    – jessepinho
    Nov 8, 2013 at 9:37
  • If you want I can send you screens of the resulting effect. Maybe something is wrong with your implementation.
    – malex
    Nov 8, 2013 at 11:09
  • Ah... it was because I wasn't aware that the view controller has to be full screen. (See Mr. T's comment.)
    – jessepinho
    Nov 9, 2013 at 8:53
1

I found this elegant and simple solution for iOS 7 and above!

For iOS 8 Apple added UIModalPresentationOverCurrentContext, but it does not work for iOS 7 and prior, so I could not use it for my case.

Please, create the category and put the following code.

.h file

typedef void(^DismissBlock)(void);

@interface UIViewController (Ext)

- (DismissBlock)presentController:(UIViewController *)controller
              withBackgroundColor:(UIColor *)color
                         andAlpha:(CGFloat)alpha
                presentCompletion:(void(^)(void))presentCompletion;

@end

.m file

#import "UIViewController+Ext.h"

@implementation UIViewController (Ext)

- (DismissBlock)presentController:(UIViewController *)controller
              withBackgroundColor:(UIColor *)color
                         andAlpha:(CGFloat)alpha
                presentCompletion:(void(^)(void))presentCompletion
{
    controller.modalPresentationStyle = UIModalPresentationCustom;

    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    __block UIView *overlay = [[UIView alloc] initWithFrame:keyWindow.bounds];
    if (color == nil) {
        color = [UIColor blackColor];
    }
    overlay.backgroundColor = color;
    overlay.alpha = alpha;

    if (self.navigationController != nil) {
        [self.navigationController.view addSubview:overlay];
    }
    else if (self.tabBarController != nil) {
        [self.tabBarController.view addSubview:overlay];
    }
    else {
        [self.view addSubview:overlay];
    }

    self.modalPresentationStyle = UIModalPresentationCurrentContext;
    [self presentViewController:controller
                       animated:true
                     completion:presentCompletion];

    DismissBlock dismissBlock = ^(void) {
        [self dismissViewControllerAnimated:YES completion:nil];
        [UIView animateWithDuration:0.25
                         animations:^{
                             overlay.alpha = 0;
                         } completion:^(BOOL finished) {
                             [overlay removeFromSuperview];
                         }];
    };
    return dismissBlock;
}

@end

Note: it works also for navigationContoller, tabBarController.

Example of usage:

       // Please, insure that your controller has clear background
       ViewController *controller = [ViewController instance];
        __block DismissBlock dismissBlock = [self presentController:controller
                                                withBackgroundColor:[UIColor blackColor]
                                                           andAlpha:0.5
                                                  presentCompletion:nil];
        // Supposed to be your controller's closing callback
        controller.dismissed = ^(void) {
            dismissBlock();
        };

Enjoy it! and please, leave some feedbacks.

0

This is the best and cleanest way I found so far:

@protocol EditLoginDelegate <NSObject>

- (void)dissmissEditLogin;

@end

- (IBAction)showtTransparentView:(id)sender {

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"foo bar"
                                                         delegate:self
                                                cancelButtonTitle:@"cancel"
                                           destructiveButtonTitle:@"destructive"
                                                otherButtonTitles:@"ok", nil];

    [actionSheet showInView:self.view];

}

- (void)willPresentActionSheet:(UIActionSheet *)actionSheet{

    UIStoryboard *loginStoryboard     = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
    self.editLoginViewController      = [loginStoryboard instantiateViewControllerWithIdentifier:@"EditLoginViewController"];

    self.editLoginViewController.delegate = self;

    [self.editLoginViewController viewWillAppear:NO];
    [actionSheet addSubview:self.editLoginViewController.view];
    [self.editLoginViewController viewDidAppear:NO];
}
0

The best solution I have come across is to use the addChildViewController method. Here is an excellent example : Add a child view controller's view to a subview of the parent view controller

0

I try to use multiple methods to solve but still failed, the follow code implemented finally.

The resolution by Swift:

// A.swift init method
modalPresentationStyle = .currentContext // or overCurrentContent
modalTransitionStyle = .crossDissolve // dissolve means overlay

then in B view controller:

// B.swift
let a = A()
self.present(a, animated: true, completion: nil)
1
  • 1
    You have to make the ViewController 's view 's backgroundColor to be transparent too. view.backgroundColor = UIColor.clear May 28, 2019 at 1:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.