Wednesday, 13 May 2009

Running a UIAlertView modally

The funny thing about UIAlertView (and other iPhone modal interfaces), is that they don't actually run modally; in other words, you can't do something simple like this:
bool bResult = [myUIAlertView runModal];


Rather, the UIAlertView has a show method ... which shows the dialog, but which doesn't simply hang around and give you a result when done.

What you need to do in this situation, is create a delegate to handle the message generated when the UIAlertView button is pressed; and you must then provide you own modal processing loop!

Here is a simplified version of what you need to do. Spot the code loop that makes it all run modally!

// 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:message delegate:lpDelegate cancelButtonTitle:cancel otherButtonTitles:ok,nil];

[lpAlertView show];

// Run modally!
// 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];
MySleepMilli(10);
}

// Grab the result from our delegate (via a custom property)
int nResult = [lpDelegate result];

// Tidy up!
[lpAlertView release];
[lpDelegate release];


Hope that helps!

4 comments:

PhoC++ Framework said...

Hi,

Where is the code of
MySleepMilli(10); function ?

thanks,

Pete Cole said...

Hi!

That is just a simple function that wraps-around nanosleep ...

http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man2/nanosleep.2.html

I just did a quick look and found various example usages of nanosleep... very easy to use.

Hoping that helps!

Best wishes,

Pete

Anonymous said...

Many thanks for your post! Helped me a lot!

Pete Cole said...

Happy to help! :)