UIAlertView卒稳、UIActionSheet、UIAlertController他巨、KVO 使用Block簡(jiǎn)單封裝充坑。

簡(jiǎn)單的封裝UIAlertView、UIActionSheet染突、UIAlertController捻爷、KVO粘姜。封裝之后不使用代理己莺,使用block直接調(diào)用響應(yīng)事件劳坑。

直接提供Demo地址:SimpleBlock

1崭添、UIAlertView 封裝

1货矮、 靜態(tài)方法Block實(shí)現(xiàn)。
typedef void (^ClickAtIndexBlock)(NSInteger buttonIndex);

@interface KAlertView : NSObject <UIAlertViewDelegate>

+ (UIAlertView *)initWithTitle:(NSString *)title
                        message:(NSString *)messge
              cancleButtonTitle:(NSString *)cancleButtonTitle
              OtherButtonsArray:(NSArray *)otherButtons
                  clickAtIndex:(ClickAtIndexBlock)clickAtIndex;

@end

初始化方法薪贫,加一個(gè)Block艘狭。

static ClickAtIndexBlock _ClickAtIndexBlock;

@implementation KAlertView

+ (UIAlertView *)initWithTitle:(NSString *)title
                       message:(NSString *)messge
             cancleButtonTitle:(NSString *)cancleButtonTitle
             OtherButtonsArray:(NSArray *)otherButtons
                  clickAtIndex:(ClickAtIndexBlock)clickAtIndex {
    _ClickAtIndexBlock = [clickAtIndex copy];
    
    UIAlertView  *alertView = [[UIAlertView alloc] initWithTitle:title
                                                         message:messge
                                                        delegate:self
                                               cancelButtonTitle:cancleButtonTitle
                                               otherButtonTitles: nil];
    for (NSString *otherTitle in otherButtons) {
        [alertView addButtonWithTitle:otherTitle];
    }
    [alertView show];
    return alertView;
}

#pragma mark   UIAlertViewDelegate

+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    _ClickAtIndexBlock(buttonIndex);
}

+ (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    _ClickAtIndexBlock = nil;
}

@end

注解:
我們這里的UIAlertView代理不是給的類(lèi)對(duì)象,而是給的類(lèi)本身囚霸,而類(lèi)本身也是對(duì)象腰根,是元類(lèi)的對(duì)象,所以代理方法也要改成類(lèi)本身的代理方法拓型,方能執(zhí)行额嘿。
UIAlertView的封裝就完成了,調(diào)用的時(shí)候我們就可以相對(duì)簡(jiǎn)單一點(diǎn)了劣挫。

 [KAlertView initWithTitle:@"title" message:@"message" cancleButtonTitle:@"cancle" OtherButtonsArray:@[@"sure",@"very"] clickAtIndex:^(NSInteger buttonIndex) {
        NSLog(@"--index : %ld",buttonIndex);
    }];
1册养、 Runtime Block實(shí)現(xiàn)。
@interface KRAlertView : NSObject <UIAlertViewDelegate>

typedef void (^ClickAtIndexBlock)(NSInteger buttonIndex);

+ (UIAlertView *)initWithTitle:(NSString*)title
                       message:(NSString *)messge
             cancleButtonTitle:(NSString *)cancleButtonTitle
             OtherButtonsArray:(NSArray*)otherButtons
                  clickAtIndex:(ClickAtIndexBlock) clickAtIndex;

@end

和第一個(gè)實(shí)現(xiàn)方法一樣压固,加一個(gè)block 一個(gè)初始化

#import <objc/runtime.h>

const char *KUIAlertView_runtime_key = "KUIAlertView_runtime_key";

@interface UIAlertView (KRAlertView)

- (void)setClickBlock:(ClickAtIndexBlock)block;

- (ClickAtIndexBlock)clickBlock;

@end

@implementation UIAlertView(KRAlertView)

- (void)setClickBlock:(ClickAtIndexBlock)block {
    objc_setAssociatedObject(self, KUIAlertView_runtime_key, block, OBJC_ASSOCIATION_COPY);
}

- (ClickAtIndexBlock)clickBlock {
    return objc_getAssociatedObject(self, KUIAlertView_runtime_key);
}

@end

@implementation KRAlertView 

+ (UIAlertView *)initWithTitle:(NSString*)title
                       message:(NSString *)messge
             cancleButtonTitle:(NSString *)cancleButtonTitle
             OtherButtonsArray:(NSArray*)otherButtons
                  clickAtIndex:(ClickAtIndexBlock) clickAtIndex {
    
    UIAlertView  *alerView = [[UIAlertView alloc] initWithTitle:title message:messge delegate:self cancelButtonTitle:cancleButtonTitle otherButtonTitles: nil];
    alerView.clickBlock = clickAtIndex;
    for (NSString *otherTitle in otherButtons) {
        [alerView addButtonWithTitle:otherTitle];
    }
    [alerView show];
    return alerView;
}

#pragma mark   UIAlertViewDelegate

+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.clickBlock) {
        alertView.clickBlock(buttonIndex);
    }
}

實(shí)際上runtime實(shí)現(xiàn)的主要思想就是給UIAlertView的類(lèi)別加一個(gè)block屬性球拦。然后就可以直接使用這個(gè)屬性,從而調(diào)用block邓夕。
這里面的主要思想是runtime的關(guān)聯(lián)屬性

    objc_setAssociatedObject(self, KUIAlertView_runtime_key, block, OBJC_ASSOCIATION_COPY);
  將某個(gè)值跟某個(gè)對(duì)象關(guān)聯(lián)起來(lái)刘莹,將某個(gè)值存儲(chǔ)到某個(gè)對(duì)象中
    // 第一個(gè)參數(shù):給哪個(gè)對(duì)象添加屬性
    // 第二個(gè)參數(shù):屬性名稱(chēng)
    // 第三個(gè)參數(shù):屬性值
    // 第四個(gè)參數(shù):保存策略
  objc_getAssociatedObject(self, KUIAlertView_runtime_key);
  獲取相應(yīng)對(duì)象的關(guān)聯(lián)值。

調(diào)用和第一種方法相同焚刚。

2点弯、UIActionSheet 封裝

UIActionSheet 實(shí)現(xiàn)方法和UIAlertView相同,但是這里提供一個(gè)不需要靜態(tài)方法矿咕,使用runtime的實(shí)現(xiàn)方式抢肛。首先創(chuàng)建一個(gè)類(lèi)別,具體代碼如下碳柱。

typedef void (^ClickAtIndexBlock)(NSInteger buttonIndex);

@interface UIActionSheet (block)

- (void)showActionSheetInView:(UIView *)showView clickCompleteBlock:(ClickAtIndexBlock)block;

@end
#import <objc/runtime.h>

static void *key = "KActionSheet_runtime_key";

@implementation UIActionSheet (block)

- (void)showActionSheetInView:(UIView *)showView clickCompleteBlock:(ClickAtIndexBlock)block {
    if (block) {
        objc_removeAssociatedObjects(self);
        objc_setAssociatedObject(self, key, block, OBJC_ASSOCIATION_COPY);
        self.delegate = (id<UIActionSheetDelegate>)self;
    }
    [self showInView:showView];
}

#pragma mark UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    ClickAtIndexBlock block = objc_getAssociatedObject(self, key);
    if (block) {
        block(buttonIndex);
    }
}

@end

原理類(lèi)似捡絮,只是這種方法調(diào)用相對(duì)其他兩種方法多一句話(huà)如下

 UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"title" delegate:nil cancelButtonTitle:@"cancel" destructiveButtonTitle:nil otherButtonTitles:@"1",@"2", nil];
 [actionSheet showActionSheetInView:self.view clickCompleteBlock:^(NSInteger buttonIndex) {
        NSLog(@"--- %ld",buttonIndex);
    }];

3、UIAlertController 封裝

ios8之后不是推薦使用這個(gè)控件嗎莲镣,當(dāng)然這個(gè)功能相對(duì)比UIAlertView和UIActionSheet要強(qiáng)大福稳,所以我也就稍微封裝一下。這個(gè)封裝就沒(méi)有runtime瑞侮,也沒(méi)有使用類(lèi)對(duì)象了的圆,直接上代碼。

#import <UIKit/UIKit.h>

typedef void (^ClickAlertBlock)(NSString *title);

@interface KAlertController : NSObject

+ (UIAlertController *)showAlertWith:(UIViewController *)showController
                               title:(NSString *)title
                             message:(NSString *)message
                         cancleTitle:(NSString *)cancleTitle
                         actionTitle:(NSArray *)titleArrary
                           alertType:(UIAlertControllerStyle)alerType
                  andClickAlertBlock:(ClickAlertBlock)block;


@end
@implementation KAlertController

+ (UIAlertController *)showAlertWith:(UIViewController *)showController
                               title:(NSString *)title
                             message:(NSString *)message
                         cancleTitle:(NSString *)cancleTitle
                         actionTitle:(NSArray *)titleArrary
                           alertType:(UIAlertControllerStyle)alerType
                  andClickAlertBlock:(ClickAlertBlock)block {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:alerType];
    for (NSString *actionTitle in titleArrary) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (block) {
                block(actionTitle);
            }
        }];
        [alertController addAction:action];
    }
    UIAlertAction *action = [UIAlertAction actionWithTitle:cancleTitle style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block(cancleTitle);
        }
    }];
    [alertController addAction:action];
    [showController presentViewController:alertController animated:YES completion:nil];
    return alertController;
}

@end

調(diào)用也是一句話(huà)半火,根據(jù)枚舉調(diào)用出來(lái)你想要的越妈,這里只舉例UIAlertVIew

   [KAlertController showAlertWith:self
                              title:@"title"
                            message:@"message"
                        cancleTitle:@"cancle"
                        actionTitle:@[@"1",@"2"]
                          alertType:UIAlertControllerStyleAlert
                 andClickAlertBlock:^(NSString *title) {
        NSLog(@"title   :%@",title);
    }];

4、KVO Block調(diào)用

原理和以上類(lèi)似钮糖,只需要加一個(gè)NSObject類(lèi)別

typedef void (^CompleteChangeBlock)(id _Nonnull obj, id _Nonnull oldVal, id _Nonnull newVal);

@interface NSObject (KVO)

- (void)addObserver:(NSObject *_Nullable)observer
         forKeyPath:(NSString *_Nullable)keyPath
completeChangeBlock:(CompleteChangeBlock _Nullable )block;

@end

static CompleteChangeBlock _CompleteChangeBlock;

@implementation NSObject (KVO)

- (void)addObserver:(NSObject *_Nullable)observer
         forKeyPath:(NSString *_Nullable)keyPath
completeChangeBlock:(CompleteChangeBlock _Nullable )block {
    
    _CompleteChangeBlock = block;
    [self addObserver:observer forKeyPath:keyPath options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)contextt {
    if (_CompleteChangeBlock) {
        _CompleteChangeBlock(object,change[@"old"],change[@"new"]);
    }
}

@end

調(diào)用:

 [self addObserver:self forKeyPath:@"number" completeChangeBlock:^(id  _Nonnull obj, id  _Nonnull oldVal, id  _Nonnull newVal) {
        NSLog(@"obj :%@   old:  %@    new: %@",obj,oldVal,newVal);
 }];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末梅掠,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌阎抒,老刑警劉巖酪我,帶你破解...
    沈念sama閱讀 221,888評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異挠蛉,居然都是意外死亡祭示,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén)谴古,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人稠歉,你說(shuō)我怎么就攤上這事掰担。” “怎么了怒炸?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,386評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵带饱,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我阅羹,道長(zhǎng)勺疼,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,726評(píng)論 1 297
  • 正文 為了忘掉前任捏鱼,我火速辦了婚禮执庐,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘导梆。我一直安慰自己轨淌,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,729評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布看尼。 她就那樣靜靜地躺著递鹉,像睡著了一般。 火紅的嫁衣襯著肌膚如雪藏斩。 梳的紋絲不亂的頭發(fā)上躏结,一...
    開(kāi)封第一講書(shū)人閱讀 52,337評(píng)論 1 310
  • 那天,我揣著相機(jī)與錄音狰域,去河邊找鬼媳拴。 笑死,一個(gè)胖子當(dāng)著我的面吹牛北专,可吹牛的內(nèi)容都是我干的禀挫。 我是一名探鬼主播,決...
    沈念sama閱讀 40,902評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼拓颓,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼语婴!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,807評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤砰左,失蹤者是張志新(化名)和其女友劉穎匿醒,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體缠导,經(jīng)...
    沈念sama閱讀 46,349評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡廉羔,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,439評(píng)論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了僻造。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片憋他。...
    茶點(diǎn)故事閱讀 40,567評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖髓削,靈堂內(nèi)的尸體忽然破棺而出竹挡,到底是詐尸還是另有隱情,我是刑警寧澤立膛,帶...
    沈念sama閱讀 36,242評(píng)論 5 350
  • 正文 年R本政府宣布揪罕,位于F島的核電站,受9級(jí)特大地震影響宝泵,放射性物質(zhì)發(fā)生泄漏好啰。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,933評(píng)論 3 334
  • 文/蒙蒙 一儿奶、第九天 我趴在偏房一處隱蔽的房頂上張望框往。 院中可真熱鬧,春花似錦廓握、人聲如沸搅窿。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,420評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)男应。三九已至,卻和暖如春娱仔,著一層夾襖步出監(jiān)牢的瞬間沐飘,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,531評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工牲迫, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留耐朴,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,995評(píng)論 3 377
  • 正文 我出身青樓盹憎,卻偏偏與公主長(zhǎng)得像筛峭,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子陪每,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,585評(píng)論 2 359

推薦閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)影晓、插件镰吵、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,120評(píng)論 4 61
  • 用到的組件 1、通過(guò)CocoaPods安裝 2挂签、第三方類(lèi)庫(kù)安裝 3疤祭、第三方服務(wù) 友盟社會(huì)化分享組件 友盟用戶(hù)反饋 ...
    SunnyLeong閱讀 14,625評(píng)論 1 180
  • 狹擠的書(shū)案 躺著 一顆百香果 一顆蘋(píng)果 時(shí)不時(shí)傳來(lái) 輪胎與潮濕路面 相觸的聲音 傘願(yuàn)不願(yuàn)意 全化為黑色 百香果已乾...
    我是思無(wú)垠閱讀 200評(píng)論 0 1
  • 這幾天看了王陽(yáng)明心學(xué),感觸很多饵婆。 王陽(yáng)明是“立言勺馆、立德、立功”的三不朽圣人侨核。他精通儒草穆、道、佛芹关,是陸王心學(xué)的集大成者...
    蓋子同學(xué)閱讀 1,532評(píng)論 4 5
  • 根據(jù)公司不同的發(fā)展階段實(shí)施管理侥衬,既要有嚴(yán)苛的制度原則管理,又有溫暖體恤下屬的人性化管理跑芳,這樣才能成為優(yōu)秀的管理者轴总。
    伊森田慧慧閱讀 125評(píng)論 0 0