iOS開發(fā)中不想用delegate協(xié)議方法怎么辦?

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本篇文章在《iOS開發(fā)之Runtime常用示例總結(jié)》基礎(chǔ)上修改,地址是「:」http://www.cocoachi...
    小__小閱讀 1,916評論 1 3
  • Objective-C作為面向?qū)ο缶幊?,“對象”(object)就是“基本構(gòu)造單元”(building block...
    Mark_Lin閱讀 407評論 0 1
  • Lancy's Blog Blog Archives About MeTwitterWeiboGitHubRSS ...
    其實也沒有閱讀 5,635評論 0 24
  • 內(nèi)心真正的聲音 總能聽到別人說:我明明很努力了,可為什么就是不行? 看在眼里,“這個孩子真的特別努力,唉,就是做不...
    扉雪倪塵閱讀 277評論 0 1
  • 青蛙見到井中的藍天 呱呱— 傲慢地鼓起眼睛 呱呱— 它猛地向上跳起 撲通— 深深地跌入水中 1984
    開宗明義閱讀 124評論 0 1

友情鏈接更多精彩內(nèi)容