在項目中我把對話框的彈出與點擊事件通過一個工具類給封裝起來了,重要的是要在調用這個工具類的時候實現工具類中的協議,這個協議的方法是為了告訴頁面到底點擊了哪種對話筐的哪一個button,然後頁面中可以根據傳過去的不同值做出不同的事件響應,代碼如下:
.h文件
[cpp]
#import <Foundation/Foundation.h>
@protocol myAlertviewutilDelegate <NSObject>
-(void)myalertviewbuttonclik:(int)num;
@end
@interface AlertViewUtil : NSObject<UIAlertViewDelegate> {
//自定義的對話筐協議
id<myAlertviewutilDelegate> utildelegate;
UIAlertView *myonealertview;//一個按鈕的對話筐
UIAlertView *mytwoalertview;//兩個按鈕的對話筐
UIAlertView *mythreealertview;//三個按鈕的對話筐
}
@property(nonatomic,retain) id<myAlertviewutilDelegate> utildelegate;
-(void)alertviewutilone:(NSString *)buttontitleone addmessage:(NSString *)message;
-(void)alertviewutiltwo:(NSString *)buttontitleone twobutton:(NSString *)buttontitletwo addmessage:(NSString *)message;
-(void)alertviewutilthree:(NSString *)buttontitleone twobutton:(NSString *)buttontitletwo threebutton:(NSString *)buttontitlethree addmessage:(NSString *)message;
@end
.m文件
[cpp]
#import "AlertViewUtil.h"
@implementation AlertViewUtil
@synthesize utildelegate;
-(void)dealloc{
[utildelegate release];
[super dealloc];
}
//實現系統對話筐協議中的button點擊方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
//點擊的是第一個alertview
if (alertView == myonealertview) {
if (buttonIndex == 0) {
[self.utildelegate myalertviewbuttonclik:11];
}
[myonealertview release];
}
//點擊的是第二個alertview
else if (alertView == mytwoalertview) {
if (buttonIndex == 0) {
[self.utildelegate myalertviewbuttonclik:21];
}
else if(buttonIndex == 1){
[self.utildelegate myalertviewbuttonclik:22];
}
[mytwoalertview release];
}
//點擊的是第三個alertview
else if (alertView == mythreealertview) {
if (buttonIndex == 0) {
[self.utildelegate myalertviewbuttonclik:31];
}
else if(buttonIndex == 1){
[self.utildelegate myalertviewbuttonclik:32];
}
else if(buttonIndex == 2){
[self.utildelegate myalertviewbuttonclik:33];
}
[mythreealertview release];
}
}
//只有一個按鈕 的alertview
-(void)alertviewutilone:(NSString *)buttontitleone addmessage:(NSString *)message{
myonealertview = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:buttontitleone, nil];
[myonealertview show];
}
//兩個按鈕 的alertview
-(void)alertviewutiltwo:(NSString *)buttontitleone twobutton:(NSString *)buttontitletwo addmessage:(NSString *)message{
mytwoalertview = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:buttontitleone,buttontitletwo, nil];
[mytwoalertview show];
}
//三個按鈕 的alertview
-(void)alertviewutilthree:(NSString *)buttontitleone twobutton:(NSString *)buttontitletwo threebutton:(NSString *)buttontitlethree addmessage:(NSString *)message{
mythreealertview = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:nil otherButtonTitles:buttontitleone,buttontitletwo,buttontitlethree, nil];
[mythreealertview show];
}
@end
摘自 RiverAM的專欄