UIGestureRecognizer
緩解UIGestureRecognizer的操作壓力不脯,用一個block解決掉,不同的手勢間的調用掂榔。
主要代碼
#import "UIGestureRecognizer+block.h"
#import <objc/runtime.h>
#import <objc/message.h>
static const int target_key;
@implementation UIGestureRecognizer (block)
+(instancetype)xjg_gestureRecognizerWithActionBlcok:(XJGestureBlock)block{
return [[self alloc]initWithActionBlock:block];
}
-(instancetype)initWithActionBlock:(XJGestureBlock)block{
self = [self init];//先init初始化成功禁添,調用的-方法表示這個self已經是一個實例,每次將實例和block綁定是钥。如果用類對象綁定就只能產生一種效果不行~
[self addActionBlcok:block];
[self addTarget:self action:@selector(invoke:)];
return self;
}
- (void)addActionBlcok:(XJGestureBlock)block{
if(block){
objc_setAssociatedObject(self, &target_key, block, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
}
- (void)invoke:(id)sender{
XJGestureBlock block=objc_getAssociatedObject(self, &target_key);
if(block)
block(sender);
}
@end
UIAlertView
多個alertview造成代碼冗余
//調用代碼
- (void)firstClick{
UIAlertView *al = [[UIAlertView alloc]initWithTitle:@"first" message:@"ok" delegate:self cancelButtonTitle:@"cancle" otherButtonTitles:@"OK", nil];
al.block = ^(UIAlertView *alert,NSUInteger index){
if(index ==1)
NSLog(@"001");
};
[al show];
}
//類別代碼
#import "UIAlertView+block.h"
#import <objc/runtime.h>
#import <objc/message.h>
@interface UIAlertView ()<UIAlertViewDelegate>
@end
@implementation UIAlertView (block)
- (void)setBlock:(JGAlertBlock)block{
objc_setAssociatedObject(self, @selector(block), block, OBJC_ASSOCIATION_COPY_NONATOMIC);
self.delegate = self;
}
- (JGAlertBlock)block{
return objc_getAssociatedObject(self, @selector(block));
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
if(self.block)
self.block(alertView,buttonIndex);
}
@end
github源碼
看了這個風格你就能理解為什么蘋果iOS9要廢棄alertview轉型UIAlertViewController掠归,在多個alert實在是很難管理伙菜,好多delegate绩鸣,代碼冗余。
上面是兩種不同的使用風格冀自,第一個在非代理情況下給不同的手勢填了了一個block弹囚。區(qū)分多個手勢
第二個在有代理情況下區(qū)分不同的alert厨相,都是使用了associated特性。方式卻有不同鸥鹉。仔細思考