Talk Funnel

Ramin Firoozye’s Public Whisperings

Semi-Modal (Transparent) Dialogs on the iPhone

11 comments (+)

Popping up a modal dialog on the iPhone is a fairly straightforward process:


	modalDialogViewController *modalController = [[modalDialogViewController alloc]
            initWithNibName:@"modalDialogView" bundle:nil];
	[self presentModalViewController:modalController animated:YES];
	[modalController release];

Dismissing it then is a simple matter of the modalController invoking:


	[self dismissModalViewControllerAnimated:YES];

But what if you want to show only half a page’s worth or maybe you need the underlying view to continue being available for user viewing or interaction. Or maybe you want to show a pop-up toolbar where users are asked to choose something before continuing. You might think “Aha! I’ll just have my modal dialog view be half as tall and make the background transparent.”

Go ahead, give it a try. We’ll wait… (* … the girl from Ipanema goes walking … *)

So now you know that the standard modal dialog can only be full-screen and maintains a solid black background. What’s more you can’t interact with what’s behind it because, you know it’s modal — and modal means users shouldn’t be able to do anything else until they’re done with the front-most task (unless you’re the search box in the Contacts app in which case apparently it’s OK to be kindasortamodal).

So what we’re going to do is have a view that can be modal but takes only part of the top view, the space above it remaining visible. What’s more, you can choose to have it so tapping on the background view hides the modal view, or even go full-bore and let the background remain responsive to user input. This technically makes the view semi-modal so let’s ignore the sirens and the UI Police banging on the door and go with that.

The first thing you need is a view that has something interactive on it. The easiest way to build one is in interface builder, so go ahead and make yourself one. For the sake of expedience make it only a fraction of the screen. Here’s an example of a half-height view along with some user controls. The background is set to fully transparent. The view is connected to a UIViewController that reacts to user input:

modalib.png

In this case, the view is the same height as the whole screen because we want the upper portion to be see-through but not react to user input. If we wanted it to be truly interactive, we could make the view height be as tall as the actual content (i.e. half-screen) but that would make it a bit strange for the user because it would be hard to tell apart the actual content from the modal view. But hey, it’s your app. You can do what you want.

Another option is to set the background of this view black and partially transparent. That would look cool and show a nice smoky cover while we’re in modal mode… unless you’re mucking with color (like we are in this example) in which case it’s best to leave it fully transparent.

Next throw the following code in the parent UIViewController. Load up the UIViewcontroller/UIView you just created and pass the view to this routine instead of calling the standard presentModalViewController method (substitute your application delegate for MyAppDelegate):


    // Use this to show the modal view (pops-up from the bottom)`
    - (void) showModal:(UIView*) modalView
    {
    	UIWindow* mainWindow = (((MyAppDelegate*) [UIApplication sharedApplication].delegate).window);

    	CGPoint	middleCenter = modalView.center;
    	CGSize offSize = [UIScreen mainScreen].bounds.size;
    	CGPoint offScreenCenter = CGPointMake(offSize.width / 2.0, offSize.height * 1.5);
    	modalView.center = offScreenCenter; // we start off-screen
    	[mainWindow addSubview:modalView];

    	// Show it with a transition effect
    	[UIView beginAnimations:nil context:nil];
    	[UIView setAnimationDuration:0.7]; // animation duration in seconds
    	modalView.center = middleCenter;
    	[UIView commitAnimations];
    }

What this does is add your view as a top-level above the main window, effectively rendering it modal. It also uses Core Animation to move the window from offscreen bottom up until it’s fully shown. You should adjust the timing to suit your view’s actual height. I’ve found that the taller the semi-modal view, the more time you should give it to become fully visible.

Now let’s go through the hiding action. Note that we use the animation completion handler to do the actual removing of the item from the parent view and cleaning up. We also use the context parameter of the animation call (which was thoughtfully provided for exactly this sort of thing) to keep track of what view to clean up afterward:


    // Use this to slide the semi-modal view back down.
    - (void) hideModal:(UIView*) modalView
    {
    	CGSize offSize = [UIScreen mainScreen].bounds.size;
    	CGPoint offScreenCenter = CGPointMake(offSize.width / 2.0, offSize.height * 1.5);
    	[UIView beginAnimations:nil context:modalView];
    	[UIView setAnimationDuration:0.7];
    	[UIView setAnimationDelegate:self];
    	[UIView setAnimationDidStopSelector:@selector(hideModalEnded:finished:context:)];
    	modalView.center = offScreenCenter;
    	[UIView commitAnimations];
    }

    - (void) hideModalEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
    {
     UIView* modalView = (UIView *)context;
    	[modalView removeFromSuperview];
    	[modalView release];
    }

What I’m not showing you here is the way to trigger the show/hide action. That’s entirely up to you. In standard iPhone modal dialogs this is often a button in the toolbar or navigation bar. In the case of the semi-modal dialog, however, you have even more flexibility. Basically it comes down to the show/hide elements being:

  • Explicit: Provide an Accept or Cancel button on your view.
  • Implicit: You can simulate an action toolbar that shows and hides this way. Put a row of buttons on the view and wire it so tapping each one invokes hideModal before going on to the actual action.
  • Other: Tapping anywhere else on the screen dismisses the dialog. You can do this by placing a full-screen sized view (or custom transparent button) behind your modal dialog and wiring it so it a tap-down action dismisses the dialog . For best results, try making this full-screen view black and semi-transparent (e.g. opacity=0.2). This way the user’s main view darkens so they get a sense your modal dialog is in focus but they still get to see what’s behind.

Here’s a movie of the above semi-modal view in action. It lets the user select a color then confirm or cancel the action. The modal view in this case also has interactive controls on it. As the user changes color the background image changes in real-time so they can visualize what the end-result will be like. Once they’re done they can tap the checkbox or X/cancel buttons to make the modal go away.

modalmovie.png

Play movie

The semi-modal dialog is a handy UI interaction component but it’s important to think about how to dismiss the dialog and what to allow in the rest of the visible region on the main window to avoid confusing the user. Also note that there are no restrictions on the shape or size of the overlay view as long as the background color is set to [UIColor clearColor]. You can use the same method for irregularly shaped pop-ups.

Go nuts and have fun.

Written by ramin

September 29th, 2009 at 7:50 pm

Posted in iphone

Tagged with ,

11 Responses to 'Semi-Modal (Transparent) Dialogs on the iPhone'

Subscribe to comments with RSS

  1. ramin-
    This is a great tutorial, thanks much. I’m an iPhone newbie and I’m failing to get this to work- when I run it with a view that otherwise works with ‘presentModalViewController’, I get no exceptions, but the view never displays (though it does initialize, I’ve verified that in the debugger). My one difference is that my main view controller is a UITabBarController. I’ve experimented with various combinations but can’t come up with anything that actually shows the view.

    Any general thoughts would be appreciated.

    Thanks,
    Ken

    Ken

    19 Oct 09 at 11:53 pm

  2. 10/10. Great tutorial :-)

    Vish

    22 Oct 09 at 3:18 am

  3. im confused, how go you call this from the ibaction of a button?

    dep

    12 Nov 09 at 11:21 am

  4. @ken You’ll want to put the showModal/hideModal routines inside your UITabBarController-derived class then pass them the view that has the stuff you want to show (which itself could be lazy-loaded from a nib file).

    The showModal code adds the semi-modal view on top of the main window so it should show up on top of everything else. It shouldn’t make any difference what’s underneath it.

    Hope this helps.

    @dep To invoke this you’ll need an IBAction method called, say, “showPanel” in your UIViewController-derived class. Wire the button to the showPanel routine. Inside showPanel you would load up your view and call the showModal method and pass it along. Wire up the close button to a “closePanel” IBAction method that calls the hidePanel method.

    ramin

    12 Nov 09 at 4:46 pm

  5. Great tutorial. Thanks! I was stuck on the modal view taking up the entire screen. This fixes the problem nicely.

  6. How would I call this from the -(void) viewdidload method?

    Jason

    28 Nov 09 at 9:14 pm

  7. I was wondering if you had the project files for this cause i am a Newbie and really want to add this effect. Thanks in advance.

    Jason

    29 Nov 09 at 5:00 pm

  8. very nice, exactly what I was looking for :)

    but I am messing around with that transparency stuff: if I set the view alpha of the view below 1, all elements on it will also be semi-transparent. what am I doing wrong??

    jotwee

    29 Jan 10 at 3:32 am

  9. btw:
    if you want to flip it up and down and up again, you have to reset the center in -(void)hideModalEnded:

    - (void) hideModalEnded:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
    {
    UIView* modalView = (UIView *)context;
    [modalView removeFromSuperview];
    CGSize offSize = [UIScreen mainScreen].bounds.size;
    CGPoint middleCenter = CGPointMake(offSize.width / 2.0, offSize.height / 2.0);
    modalView.center = middleCenter;
    [modalView release];
    }

    jotwee

    29 Jan 10 at 5:03 am

  10. @Jason: It should be pretty straightforward to use. Just create a class derived from UIViewController, add the above methods to it and then call those methods to show and hide the view as a modal.

    @jotwee: To adjust only the transparency of the background, try setting the alpha of the background view to < 1.0 *before* adding any subviews to it.

    On flipping up/down/up: not sure why you’d want to do that, because if you’re holding a reference to the modalView so it can be reused later, the ’showModal’ routine sets the center before it starts off. And if you do it in the hideModalEnded after it’s been removed from the subview then it won’t be visible. Maybe I’m not getting your usage scenario.

    ramin

    2 Feb 10 at 12:20 am

  11. @ramin
    ??
    first time show: middleCenter = middle of the screen
    second time show: middleCenter = offScreenCenter

    after hiding, you have to reset the center (when the view is not visible)

    jotwee

    24 Feb 10 at 9:10 am

Leave a Reply