Monday, May 9, 2011

Modal Views

Many apps that require the user to sign in present a view sliding up from the bottom of the screen, this is called a modal view. Sliding-up is just one way a modal view can be presented, other ways are partial curl like in the maps app, the flipping view when you tap the 'i' button etc.

Partial curl in maps
So the idea of a modal view is to present a temporary view which asks the user to perform some action and then the view is dismissed to reveal the original view. The idea of a sign in perfectly fits into the reason of a modal view being presented, the user is doing something that requires signing in, the modal view is presented, the user logs in and the original screen comes back to let the user continue his/her activity in the app.

So let us get to know how is this done in code. First you'll need two view controllers, one will be the main view and the second will be the modal view. Set up the first view controller to have a button which is hooked up to a method called buttonPressed. In this method put the following code to present the second view modally.

SecondView *modalViewController = [[SecondView alloc] init];
[modalViewController setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[self presentModalViewController:modalViewController animated:YES];

If everything goes well when you build the app and press the button, a new view should slide from below. 

To make the view appear in other styles like horizontal flip use the following pass the following parameters instead of UIModalTransitionStyleCoverVertical
  • Horizontal flip - UIModalTransitionStyleFlipHorizontal
  • Partial curl - UIModalTransitionStylePartialCurl
  • Dissolve - UIModalTransitionStyleCrossDissolve
Try running the project with each of these as arguments to have a look at all the animations.

Now that we have successfully managed to present view controllers, we move on to dismissing them, that is bring back the original view on the screen from where the modal view was presented.

For this add a button in your secondView which hooks up to a method, lets call it otherButtonPressed. Include the following code in the implementation of the otherButtonPressed method.

[self dismissModalViewControllerAnimated:YES];

Run your project now and you should have a sample app which presents and dismisses your modal view. You can experiment with the parameters, try out different styles.

No comments: