国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Block支持的UIAlertView

2019-11-14 20:15:51
字體:
供稿:網(wǎng)友

開發(fā)IOS時(shí)經(jīng)常會(huì)使用到UIAlertView類,該類提供了一種標(biāo)準(zhǔn)視圖,可向用戶展示警告信息。當(dāng)用戶按下按鈕關(guān)閉該視圖時(shí),需要用委托協(xié)議(Delegate PRotocol)來處理此動(dòng)作,但是要設(shè)置好這個(gè)委托協(xié)議,就得把創(chuàng)建警告視圖和處理按鈕動(dòng)作的代碼分開。

UIAlertView *inputAlertView = [[UIAlertView alloc] initWithTitle:@"Add a new to-do item:" message:nil delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:@"Add", nil];

//UIAlertViewDelegate protocol method

- (void)alertView:(UIAlertView *)alertView clickButtonAtButtonIndex:(NSInteger)buttonIndex {

  if (buttonIndex == 0) {

    [self doCancel];

  } else {

  [self doContinue];

 }

}

假如想在一個(gè)類中處理多個(gè)UIAlertView,那么代碼會(huì)更加復(fù)雜,需要在delegate方法中加入對(duì)AlertView的tag的判斷。

如果能在創(chuàng)建UIAlertView時(shí)把處理每個(gè)按鈕的邏輯寫好,那就簡單多了,我們可以使用BLOCK來完成。

一、使用Category +Associate Object +Block

//UIAlertView+FHBlock.h

typedef void (^FHAlertViewCompletionBlock)(UIAlertView *alertView, NSInteger buttonIndex);

@interface UIAlertView (FHBlock) <UIAlertViewDelegate>

@property(nonatomic,copy) FHAlertViewCompletionBlock completionBlock;

@end

 

 

//UIAlertView+FHBlock.m

#import <objc/runtime.h>

@implementation UIAlertView (FHBlock)<UIAlertViewDelegate>

- (void)setCompletionBlock:(FHAlertViewCompletionBlock)completionBlock {

  objc_setAssociatedObject(self, @selector(completionBlock), completionBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);

  if (completionBlock == NULL) {

    self.delegate = nil;

  }

  else {

    self.delegate = self;

  }

}

- (FHAlertViewCompletionBlock)completionBlock {

  return objc_getAssociatedObject(self, @selector(completionBlock));

}

 

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickButtonAtButtonIndex:(NSInteger)buttonIndex {

  if (self.completionBlock) {

    self.completionBlock(self, buttonIndex);

  }

}

@end

 

二、inheritance+Block

//FHAlertView.h

typedef void(^AlertBlock)(UIAlert* alert,NSInteger buttonIndex);

@interface FHAlertView:UIAlertView

@property(nonatomic,copy) AlertBlock completionBlock;

 

//FHAlertView.m

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickButtonAtButtonIndex:(NSInteger)buttonIndex {

  if (self.completionBlock) {

    self.completionBlock(self, buttonIndex);

  }

}

@end

 

可以參考源碼http://blog.projectrhinestone.org/preventhandler/


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 东安县| 清原| 鄂尔多斯市| 博乐市| 安丘市| 修水县| 志丹县| 津南区| 同心县| 金湖县| 许昌县| 富顺县| 建水县| 齐河县| 芜湖县| 景泰县| 通道| 洪雅县| 临安市| 潍坊市| 云安县| 喀喇| 闻喜县| 商城县| 鲁甸县| 克什克腾旗| 东乌| 仪征市| 芜湖县| 桐庐县| 海南省| 潞西市| 浮梁县| 乌兰浩特市| 临泉县| 固阳县| 红原县| 谢通门县| 寿光市| 当阳市| 寿光市|