I am new to iPhone application development. I want to design an alert view with 2 buttons: OK
and Cancel
. When the user touches the OK
button, then I will print a message that says hello
. When they touch the Cancel
button, I will print cancel
.
Please help; how do I do this?
Banner alerts are the notifications that appear at the top of your screen while you're using another app on your iPhone or iPad. You see them most often with instant messaging apps, but they can be used for any kind of notification.
Open your phone's Settings app. Notifications. Under "Lock screen," tap Notifications on lock screen or On lock screen. Choose Show alerting and silent notifications.
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",nil];
[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.
since the chosen answer is deprecated, here is the new solution:
UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"My Alert"
message:@"This is an alert."
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {}];
[alert addAction:defaultAction];
[self presentViewController:alert animated:YES completion:nil];
As shown in iOs Developer guide.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With