Search Results

Filtered by:programming

Site Search

Search Articles.

iPhone: Modal Dialogs

Sunday 11 Apr 2010 19:48

If like me you come from a Windows programmer background then you might be surprised at the lack of support for modal dialogs in the iPhone OS. Apple provide you with a UIAlertView which is great for on screen prompts and confirmations, but using them can be quite tedious and require a lot more code than is often neccessary.

This means you can't have code like this

result = CreateModalDialog(NSTitle, NSMsg, @"Ok", @"Cancel");

Instead you have to provide delegates which are called once the user selects an option. In other words your code does not stop and wait for a return value. Whilst this has its benefits in terms of multitasking, your code can get quite messy as you chain these delegates together.

There is another way which involves creating a custom UIAlertView class and a run loop. The code should be self explanatory.

UIAlertView *alert;   
@interface MyUIAlertViewDelegate : NSObject <UIActionSheetDelegate, UIAlertViewDelegate> 
  int result;


@implementation MyUIAlertViewDelegate

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
	result = buttonIndex;

	return result;


int CreateModalDialog(NSString *title,
                      NSString *msg, 
                      NSString *ok, 
                      NSString *cancel)
	// Create an instance of a custom UIAlertViewDelegate that we use to capture
	// the events generated by the UIAlertView
	MyUIAlertViewDelegate *lpDelegate = [[MyUIAlertViewDelegate alloc] init];

	// Construct and "show" the UIAlertView (message, title, cancel, ok are all
	// NSString values created earlier in your code...)
	UIAlertView *lpAlertView = [[UIAlertView alloc] 
otherButtonTitles:ok, nil]; [lpAlertView show]; // By the time this loop terminates, our delegate will have been
// called and we can get the result from the delegate (i.e. what button was pressed...) while ((!lpAlertView.hidden) && (lpAlertView.superview!=nil)) { [[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode]; Sleep(10); } // Grab the result from our delegate (via a custom property) int nResult = [lpDelegate getResult]; // Tidy up! [lpAlertView release]; [lpDelegate release]; NSLog(@"Result: %d", nResult); return nResult; } @end;

Tags: Modal Dialogs UIAlertView iPhone programming

Comments (2)

9 Jun 2010 04:38 by Marc
Yes, this annoys me too. I just posted about it in fact and the first of my two solutions looks a lot like yours. See
5 Jul 2011 03:13 by Carli
That saves me. Thanks for being so sesnilbe!


Sites of Interest