首先,視圖控制器必須得實作協定uialertviewdelegate中的方法,并指定delegate為self,才能使彈出的alert視窗響應點選事件。
具體代碼如下:
viewcontroller.h中的代碼如下:
#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;
}