Search Results

Filtered by:Modal Dialogs

Site Search

Search Articles.



iPhone: Modal Dialogs

Sunday 11 Apr 2010 20:50

Have you ever wondered how to create modal dialogs on the iPhone? Dreamed of simply calling a confirmation dialog and getting back the user input without the need for delegates and messy code.

Read more about modal dialogs here.

Tags: Modal Dialogs UIAlertView iPhone programming

iPhone: Modal Dialogs

Sunday 11 Apr 2010 20: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");
switch(result)
{
   ....
}

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.

ModalDialog.h
UIAlertView *alert;   
    
@interface MyUIAlertViewDelegate : NSObject <UIActionSheetDelegate, UIAlertViewDelegate> 
{
  int result;
}

-(int)getResult;

@end;

ModalDialog.mm
@implementation MyUIAlertViewDelegate

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

-(int)getResult
{
	return result;
}

@end;

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] 
initWithTitle:title
message:msg
delegate:lpDelegate
cancelButtonTitle:cancel
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

Links

Sites of Interest