前言:
上篇文章写的是Runtime的一个入门教程,刚哥问我那个Associated Objects加回调是啥时候用,那我就来告诉你啦!我们在使用UIAlertView的时候用的多。
传统的UIAlertView:
在一个类中有多个UIAlertView,不同的UIAlertView对应不同的事件,我们使用的传统方法如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#pragma mark - action method - (IBAction)firstButtonClick:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil]; alertView.tag = 1001; [alertView show]; } - (IBAction)secondButtonClick:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil]; alertView.tag = 1002; [alertView show]; } - (IBAction)ThirdButtonClick:(id)sender { UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"title" message:@"message" delegate:self cancelButtonTitle:@"cancel" otherButtonTitles:@"ok", nil]; alertView.tag = 1003; [alertView show]; } #pragma mark - delegate method - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex { if (alertView.tag == 1001) { if (buttonIndex == 1) { NSLog(@"普通alertView1001执行ok"); } } else if (alertView.tag == 1002) { if (buttonIndex == 1) { NSLog(@"普通alertView1002执行ok"); } } else if (alertView.tag == 1003) { if (buttonIndex == 1) { NSLog(@"普通alertView1003执行ok"); } } } |
我们要给每个UIAlertView赋值一个tag值,在delegate方法中还要进行tag的判断以及buttonIndex的判断,太繁琐了。
着魔的UIAlertView:
下面我们使用Category和Associated Objects进行魔法修改
创建一个UIAlertView的Category
UIAlertView+ActionBlock.h
1 2 3 4 5 6 7 8 9 |
#import <UIKit/UIKit.h> typedef void (^AlertCallBack)(UIAlertView *, NSUInteger); @interface UIAlertView (ActionBlock)<UIAlertViewDelegate> @property (nonatomic, copy) AlertCallBack callBack; @end |
UIAlertView+ActionBlock.m
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
#if TARGET_IPHONE_SIMULATOR #import <objc/objc-runtime.h> #else #import <objc/runtime.h> #import <objc/message.h> تUIAlertView,不同的UIAlertView对应不同的事件,我们使用的传统方法如下:
我们要给每个UIAlertView赋值一个tag值,在delegate方法中还要进行tag的判断以及buttonIndex的判断,太繁琐了。 着魔的UIAlertView:下面我们使用Category和Associated Objects进行魔法修改 创建一个UIAlertView的Category UIAlertView+ActionBlock.h
UIAlertView+ActionBlock.m
|