首先,视图控制器必须得实现协议UIAlertViewDelegate中的方法,并指定delegate为self,才能使弹出的Alert窗口响应点击事件。
具体代码如下:
ViewController.h中的代码如下:
- #import <UIKit/UIKit.h>
-
- @interface ViewController : UIViewController<UIAlertViewDelegate>
-
- @end
ViewController.m中的详细代码:
- - (void)viewDidLoad
- {
- [super viewDidLoad];
-
-
-
- UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AlertViewTest"
- message:@"message"
- delegate:self
- cancelButtonTitle:@"Cancel"
- otherButtonTitles:@"OtherBtn",nil];
-
- alert.title = @"AlertViewTitle";
- alert.message = @"AlertViewMessage";
-
-
- alert.tag = 0;
-
- NSLog(@"%d",alert.visible);
-
- [alert addButtonWithTitle:@"addButton"];
-
- NSLog(@"number Of Buttons :%d",alert.numberOfButtons);
-
- NSLog(@"buttonTitleAtIndex1:%@",[alert buttonTitleAtIndex:1]);
- NSLog(@"buttonTitleAtIndex2:%@",[alert buttonTitleAtIndex:2]);
-
- NSLog(@"cancelButtonIndex:%d",alert.cancelButtonIndex);
-
- NSLog(@"firstOtherButtonIndex:%d",alert.firstOtherButtonIndex);
-
- [alert show];
- [alert release];
- }
-
- #pragma marks -- UIAlertViewDelegate --
- -(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- NSLog(@"clickButtonAtIndex:%d",buttonIndex);
- }
-
- -(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
- {
- NSLog(@"didDismissWithButtonIndex");
- }
-
- -(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
- {
- NSLog(@"willDismissWithButtonIndex");
- }
-
- -(void)alertViewCancel:(UIAlertView *)alertView
- {
- NSLog(@"alertViewCancel");
- }
-
- -(void)didPresentAlertView:(UIAlertView *)alertView
- {
- NSLog(@"didPresentAlertView");
- }
-
- -(void)willPresentAlertView:(UIAlertView *)alertView
- {
- NSLog(@"willPresentAlertView");
- }
-
- - (void)viewDidUnload
- {
- [super viewDidUnload];
-
-
- }
UIALertView的基本用法与UIAlertViewDelegate对对话框的事件处理方法
原文:http://www.cnblogs.com/Free-Thinker/p/7084840.html