-
Notifications
You must be signed in to change notification settings - Fork 3
/
UIAlertView+Barefoot.m
92 lines (65 loc) · 2.57 KB
/
UIAlertView+Barefoot.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
#import "UIAlertView+Barefoot.h"
#import <objc/runtime.h>
@interface UIAlertViewDelegateWrapper : NSObject
@property (copy) void(^completionBlock)(UIAlertView *alertView, NSInteger buttonIndex);
@end
@implementation UIAlertViewDelegateWrapper
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (self.completionBlock) self.completionBlock(alertView, buttonIndex);
}
- (void)alertViewCancel:(UIAlertView *)alertView {
if (self.completionBlock) self.completionBlock(alertView, alertView.cancelButtonIndex);
}
@end
@interface UIAlertViewHangaround : NSObject
@property NSString *_hash;
+ (BOOL)alertViewIsAlreadyShowing:(NSString *)hash;
@end
@implementation UIAlertViewHangaround
static NSMutableDictionary *hashes;
- (void)setHash:(NSString *)hash {
self._hash = hash;
if (!hashes) {
hashes = [NSMutableDictionary dictionary];
}
[hashes setValue:@"YES" forKey:hash];
}
+ (BOOL)alertViewIsAlreadyShowing:(NSString *)hash {
if ([hashes objectForKey:hash]) {
return YES;
}
return NO;
}
- (void)dealloc {
[hashes removeObjectForKey:self._hash];
}
@end
static const char kUIAlertViewWrapperDelegate;
static const char kUIAlertViewHangaround;
@implementation UIAlertView (Barefoot)
- (id)initWithTitle:(NSString *)title message:(NSString *)message completion:(void (^)(UIAlertView *, NSInteger))completionBlock cancelButtonTitle:(NSString *)cancelButtonTitle otherButtonTitles:(NSString *)otherButtonTitles, ... {
UIAlertViewDelegateWrapper *alertWrapper = [[UIAlertViewDelegateWrapper alloc] init];
alertWrapper.completionBlock = completionBlock;
self = [self initWithTitle:title message:message delegate:alertWrapper cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitles, nil];
if (self) {
objc_setAssociatedObject(self, &kUIAlertViewWrapperDelegate, alertWrapper, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
if (otherButtonTitles) {
NSString *buttonTitle;
va_list argumentList;
va_start(argumentList, otherButtonTitles);
while ((buttonTitle = va_arg(argumentList, NSString*))) [self addButtonWithTitle:buttonTitle];
va_end(argumentList);
}
}
return self;
}
- (void)showOne {
NSString *hash = [NSString stringWithFormat:@"%@%@", self.title, self.message];
if (![UIAlertViewHangaround alertViewIsAlreadyShowing:hash]) {
UIAlertViewHangaround *hangaround = [[UIAlertViewHangaround alloc] init];
[hangaround setHash:hash];
objc_setAssociatedObject(self, &kUIAlertViewHangaround, hangaround, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
[self show];
}
}
@end