-
Notifications
You must be signed in to change notification settings - Fork 3
/
NSObject+blcok.m
110 lines (73 loc) · 2.84 KB
/
NSObject+blcok.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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// NSObject+blcok.m
// buttonBlock
//
// Created by gitBurning on 15/1/13.
// Copyright (c) 2015年 gitBurning. All rights reserved.
//
#import "NSObject+blcok.h"
#import <UIKit/UIKit.h>
static const char * UtilityKey = "buttonBlock";
static const char * DictKey = "dict";
#define kBlockKey @"key"
@implementation NSObject (blcok)
#pragma mark---block property
- (buttonHandlerBlcok)eventHandler {
return objc_getAssociatedObject(self, &UtilityKey);
}
- (void)setEventHandler:(buttonHandlerBlcok)eventHandler {
objc_setAssociatedObject(self, &UtilityKey, eventHandler, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (eventHandler) {
if ([self isKindOfClass:[UIButton class]]) {
UIButton * button=(UIButton*)self;
[button addTarget:self action:@selector(touchUpAcntion) forControlEvents:UIControlEventTouchUpInside];
}
else if ([self isKindOfClass:[UIImageView class]] || [self isKindOfClass:[UIView class]]){
UIImageView * image=(UIImageView*)self;
image.userInteractionEnabled=YES;
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchUpAcntion)];
[image addGestureRecognizer:tap];
tap=nil;
}
if (self.evenDict) //判断 属性和方法共存的时候,清空一个
{
self.evenDict=nil;
}
}
}
#pragma mark---other property
-(NSMutableDictionary *)evenDict{
return objc_getAssociatedObject(self, &DictKey);
}
-(void)setEvenDict:(NSMutableDictionary *)evenDict{
objc_setAssociatedObject(self, &DictKey, evenDict, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(void)addHandAction:(void (^)(id))handler{
self.evenDict=[NSMutableDictionary dictionaryWithObjectsAndKeys:handler,kBlockKey, nil];
if ([self isKindOfClass:[UIButton class]]) {
UIButton * button=(UIButton*)self;
[button addTarget:self action:@selector(touchUpAcntion) forControlEvents:UIControlEventTouchUpInside];
}
else if ([self isKindOfClass:[UIImageView class]] || [self isKindOfClass:[UIView class]]){
UIImageView * image=(UIImageView*)self;
image.userInteractionEnabled=YES;
UITapGestureRecognizer * tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(touchUpAcntion)];
[image addGestureRecognizer:tap];
tap=nil;
}
if (self.eventHandler) //判断 属性和方法共存的时候,清空一个
{
self.eventHandler=nil;
}
}
#pragma mark-----evenHandler
-(void)touchUpAcntion{
if (self.eventHandler) {
self.eventHandler(self);
}
else{
void (^tag)(id sender)=self.evenDict[kBlockKey];
tag(self);
}
}
@end