hi i am new to iphone application development, i want to design an alert view, which has 2 buttons, OK and cancel. On Ok Button the i will print say an message hello and on cancel button i will print cancel.. Please help how am i to do it
+6
A:
To show the alert:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Do you want to say hello?" message:@"More info..." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Say Hello"];
[alert show];
[alert release];
To respond to whatever button was tapped:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(@"Cancel Tapped.");
}
else if (buttonIndex == 1) {
NSLog(@"OK Tapped. Hello World!");
}
}
For more information, see the UIAlertView Class Reference and the UIAlertView Delegate Protocol Reference.
Steve Harrison
2009-11-17 09:24:34
shouldn't your answer also include the necessity for <UIAlertViewDelegate> in the .h file? I realize that you reference both the class and delegate protocol, but it's easy to imagine the OP skipping that part :(
KevinDTimm
2009-11-17 09:38:27
it is better to use "buttonIndex!=alertView.cancelButtonIndex", in case you remove the cancel button later and forget to change the button indexes in the delegate call.
Felix
2009-11-17 11:04:24
Steve, you haven't included 'nil' as the final item in your list of otherButtonTitles! Therefore when this code is copied and used, it gives a warning on compile and then crashes on running...
h4xxr
2010-07-01 13:10:16
A:
Show the alert with the following snippet
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Make an informed choice" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil]; [alert show];
The delegate is set to self so when the alert is dismissed our own class will get a call back. The delegate must implement the UIAlertViewDelegate protocol.
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger) buttonIndex{ if (buttonIndex == 1) { // Do it! } else { // Cancel } }
Niels Castle
2009-11-17 09:25:33