October 19, 2010

iOS: Semi-modal date picker for iPhone

At some point you are going to want to have a view that takes up have the screen, but is semi-transparent so you can see what is going on underneath. Something like this:


‘Easy!’ you say, just make a view with a semi-transparent background on then slide it in a s a modal view. Well, give that a try. To break the suspense: It doesn’t work, iOS gives the view an opaque background as soon as it is displayed, no matter what you set in IB. In order to get this effect you need to be a bit sneaky an do the animation yourself.

For BlueTick, my iphone todoist client I needed a semi-modal date picker, so I ended up writing a class that does all this myself (Which I based off this post here). Thats it in the screenshot at the top of the post. The code is up on github, and its under the MIT-License, so go ahead and use it where ever you want.

Include like this:

    #import "TDSemiModal.h"

In order to show up your own modal view, just do this:

    [self presentSemiModalViewController:newview];

And to hide:

    [self dismissSemiModalViewController:newview];

A semi transparent ‘cover’ will be automatically put in to stop the user from interacting with the UI behind, so I recommend you set the background on your view to completely transparent.

Obviously you can create whatever semi-modal view you want, but a datepicker must be one of the most common usages, so I knocked up a class for that too.

The datepicker view itself is not too hard to use, just create and display as before:

    #import "TDDatePickerController.h"
    TDDatePickerController* datePickerView = [[TDDatePickerController alloc] 
                                  initWithNibName:@"TDDatePickerController" 
                                  bundle:nil];
    datePickerView.delegate = self;
    [self presentSemiModalViewController:datePickerView];

Then you just need to catch the following actions in your delegate when the date is actually selected:

    -(void)datePickerSetDate:(TDDatePickerController*)viewController;
    -(void)datePickerClearDate:(TDDatePickerController*)viewController;
    -(void)datePickerCancel:(TDDatePickerController*)viewController;

Easy peasy! Again its up on github so send any patches or issues over there.

  1. aarav-h reblogged this from reednj
  2. reednj posted this
blog comments powered by Disqus