<p style="color: rgb(54, 46, 43); font-family: Arial; font-size: 14px; line-height: 26px;">首先,視圖控制器必須得實現協議UIAlertViewDelegate中的方法,並指定delegate爲self,才能使彈出的Alert窗口響應點擊事件。</p><p style="color: rgb(54, 46, 43); font-family: Arial; font-size: 14px; line-height: 26px;">具體代碼如下:</p><p style="color: rgb(54, 46, 43); font-family: Arial; font-size: 14px; line-height: 26px;"></p><p class="p1" style="color: rgb(54, 46, 43); font-family: Arial; font-size: 14px; line-height: 26px;">ViewController.h中的代碼如下:</p>
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIAlertViewDelegate>
@end
ViewController.m中的詳細代碼:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib
//初始化AlertView
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"AlertViewTest"
message:@"message"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"OtherBtn",nil];
//設置標題與信息,通常在使用frame初始化AlertView時使用
alert.title = @"AlertViewTitle";
alert.message = @"AlertViewMessage";
//這個屬性繼承自UIView,當一個視圖中有多個AlertView時,可以用這個屬性來區分
alert.tag = 0;
//只讀屬性,看AlertView是否可見
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);
//顯示AlertView
[alert show];
[alert release];
}
#pragma marks -- UIAlertViewDelegate --
//根據被點擊按鈕的索引處理點擊事件
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"clickButtonAtIndex:%d",buttonIndex);
}
//AlertView已經消失時執行的事件
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(@"didDismissWithButtonIndex");
}
//ALertView即將消失時的事件
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
NSLog(@"willDismissWithButtonIndex");
}
//AlertView的取消按鈕的事件
-(void)alertViewCancel:(UIAlertView *)alertView
{
NSLog(@"alertViewCancel");
}
//AlertView已經顯示時的事件
-(void)didPresentAlertView:(UIAlertView *)alertView
{
NSLog(@"didPresentAlertView");
}
//AlertView即將顯示時
-(void)willPresentAlertView:(UIAlertView *)alertView
{
NSLog(@"willPresentAlertView");
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
原文出處:http://blog.csdn.net/enuola/article/details/7900346