iOS開發(fā)中不想用delegate協(xié)議方法怎么辦?那就用block!
前兩天在網(wǎng)上看到大神將alertView的delegate協(xié)議方法轉(zhuǎn)為block實現(xiàn),實在是大快我心(其實一開始我就不喜歡delegate的,偏向block,現(xiàn)在也在block學習路上)
先展示一下使用
UIAlertView *customAlertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"取消"otherButtonTitles:@"確定",nil];
[customAlertView showAlertViewWithCompleteBlock::^(UIAlertView*alertView,NSInteger buttonIndex) {
// code?
}];
這樣alert的delegate就不用去寫了,是不是很方便??!
這個UIAlertView+Block實現(xiàn)方式是利用runtime來實現(xiàn),在系統(tǒng)調(diào)用alert的delegate時,將其轉(zhuǎn)化為block,代碼很簡單,能想出來,卻不簡單,謝謝這位大神,代碼貼出來(詳細注釋)
新建AlertView的分類 UIAlertView+Block
.h
// 先定義一個 block結(jié)果回調(diào)
typedef void(^CompleteBlock) (UIAlertView *alertView, NSInteger buttonIndex);
@interfaceUIAlertView (Block)
// 顯示alertView
- (void)showAlertViewWithCompleteBlock:(CompleteBlock)block;
@end
.m
#import"UIAlertView+Block.h"
#import
@implementationUIAlertView (Block)
staticcharkey;
-(void)showAlertViewWithCompleteBlock:(CompleteBlock)block
{
//首先判斷這個block是否存在
if(block) {
//這里用到了runtime中綁定對象,將這個block對象綁定alertview上
objc_setAssociatedObject(self, &key,block,OBJC_ASSOCIATION_COPY);
//設(shè)置delegate
self.delegate=self;
}
//彈出提示框
[selfshow];
}
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)btnIndex
{
//拿到之前綁定的block對象
CompleteBlockblock =objc_getAssociatedObject(self, &key);
//移除所有關(guān)聯(lián)
objc_removeAssociatedObjects(self);
if(block) {
//調(diào)用block傳入此時點擊的按鈕index
block(alertView, btnIndex);
}
}
@end