天天看點

為UIAlertView添加block支援

系統自帶的UIAlertView隻能支援delegate方式. 如果你隻有一個UIAlertView這種方式可能無關緊要. 但如果你有二個或多個UIAlertView, 你需要在委托方法中進行判斷是哪個UIAlertView執行個體的産生的委托, 接着又要判斷是響應哪個button. 如果你曾經這樣做過, 想想這是多雜的代碼. Objective-C是支援塊代碼的, 如果對UIAlertView添加塊支援, 那豈不是一個美事.

這裡推薦一個開源的實作: https://github.com/jivadevoe/UIAlertView-Blocks

如果你的項目使用Cocoapods管理. 在Podfile添加下面代碼增加支援

pod "UIAlertView-Blocks", "~> 1.0"
           

再使用指令更新

pod update
           

使用方式

// 添加頭檔案
#import <UIAlertView+Blocks.h>


NSString *title = NSLocalizedString(@"Alert", nil);
NSString *message = NSLocalizedString(@"UIAlertView-Blocks", nil);
NSString *cancelButtonTitle = NSLocalizedString(@"Cancel", nil);
NSString *otherTitle = NSLocalizedString(@"OK", nil);


RIButtonItem *cancelButtonItem = [RIButtonItem itemWithLabel:cancelButtonTitle action:^{
	NSLog(@"Press Button Cancel");
}];

RIButtonItem *otherButtonItem = [RIButtonItem itemWithLabel:otherTitle action:^{
	NSLog(@"Press Button OK");
}];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message cancelButtonItem:cancelButtonItem otherButtonItems:otherButtonItem, nil];

[alert show];
           

除了這種使用方式,  UIAlertView-Blocks還支援其它方法, 可以參考一下它的github首頁.