iPhone OS SDK – UIAlert & UIAlert Action on button click

18/03/2010

Using a UIAlertView in apps is very common and surprisingly complex. Its 2 lines, but comparing to VBasic its complicated. This is done by:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Welcome to Savings Goal” message:@”Please press the red button to setup your savings goal and current amount saved.” delegate:self cancelButtonTitle:nil otherButtonTitles:@”Ok Lets Save!”,nil];
[alert show];

These two lines I keep using over and over again. They form a very common copy and paste in my projects.
More interesting is performing an action on a button click in the UIAlertView. Lets say you have 2 buttons (buttonIndex 0 and 1). use the following method to execute code on that button press.

- (void)alertView: (UIAlertView *)alertView clickedButtonAtIndex: (NSInteger)buttonIndex
{
if (buttonIndex==0) {
NSLog(@”In AlertView Delegate”);
//start a timer
timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerVoid) userInfo:nil repeats:YES];
}

}

This will start a timer (NSTimer *timer), when the first button is pressed in an UIAlert. For UIAlerts with multiple buttons, you should use the int buttonIndex to detect which button was pressed.

Thats all for today, enjoy.

No comments yet.

Write a comment:

blog comments powered by Disqus