-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathUIControl+Additions.m
91 lines (72 loc) · 2.12 KB
/
UIControl+Additions.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
//
// UIControl+Additions.m
//
// Created by Wess Cope on 6/3/11.
// Copyright 2012. All rights reserved.
//
#import <dispatch/dispatch.h>
#import <objc/runtime.h>
#import "UIControl+Additions.h"
@interface UIControlCallback : NSObject
{
@private
EventCallback callback;
UIControlEvents events;
}
- (id)initWithCallback:(EventCallback)block forEvents:(UIControlEvents)controlEvents;
- (void)execute:(id)sender;
@property (copy) EventCallback callback;
@property (assign) UIControlEvents events;
@end
@implementation UIControlCallback
@synthesize callback, events;
- (id)initWithCallback:(EventCallback)block forEvents:(UIControlEvents)controlEvents
{
self = [super init];
if(self)
{
self.callback = block;
self.events = controlEvents;
}
return self;
}
- (void)execute:(id)sender
{
EventCallback action = self.callback;
if(action)
dispatch_async(dispatch_get_main_queue(), ^{ action(sender); });
}
- (void)dealloc
{
Block_release(callback);
[super dealloc];
}
@end
@implementation UIControl(Additions)
- (void)on:(UIControlEvents)events callback:(EventCallback)callback
{
NSMutableArray *currentEvents = objc_getAssociatedObject(self, @"EventBlocks");
if(!currentEvents)
{
currentEvents = [[NSMutableArray alloc] init];
objc_setAssociatedObject(self, @"EventBlocks", currentEvents, OBJC_ASSOCIATION_COPY_NONATOMIC);
[currentEvents release];
}
UIControlCallback *element = [[UIControlCallback alloc] initWithCallback:callback forEvents:events];
[currentEvents addObject:element];
[self addTarget:element action:@selector(execute:) forControlEvents:events];
[element release];
}
- (void)remove:(UIControlEvents)events
{
NSMutableArray *currentEvents;
if ((currentEvents = objc_getAssociatedObject(self, @"EventBlocks")))
{
[currentEvents removeObjectsInArray:[currentEvents select:^BOOL(id sender) {
if ([sender isKindOfClass:[UIControlCallback class]])
return ([(UIControlCallback*)sender events] == events);
return NO;
}]];
}
}
@end