forked from TribeHR/TITokenField
-
Notifications
You must be signed in to change notification settings - Fork 1
/
TITokenField.m
1490 lines (1112 loc) · 48.4 KB
/
TITokenField.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// TITokenField.m
// TITokenField
//
// Created by Tom Irving on 16/02/2010.
// Copyright 2012 Tom Irving. All rights reserved.
//
#import "TITokenField.h"
#import <QuartzCore/QuartzCore.h>
BOOL isIOS7OrGreater() {
static dispatch_once_t once;
static BOOL isIOS7;
dispatch_once(&once, ^ {
NSString* majorVersion = [[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."][0];
isIOS7 = [majorVersion integerValue] >= 7;
});
return isIOS7;
}
@interface TITokenField ()
@property (nonatomic, assign) BOOL forcePickSearchResult;
@end
@interface TIFlatToken : TIToken
@end
//==========================================================
#pragma mark - TITokenFieldView -
//==========================================================
@interface TITokenFieldView (Private)
- (void)setup;
- (NSString *)displayStringForRepresentedObject:(id)object;
- (NSString *)searchResultStringForRepresentedObject:(id)object;
- (void)setSearchResultsVisible:(BOOL)visible;
- (void)resultsForSearchString:(NSString *)searchString;
- (void)presentpopoverAtTokenFieldCaretAnimated:(BOOL)animated;
- (void)setScrollEnabledIfAllowed:(BOOL)enableScrolling;
@end
@implementation TITokenFieldView {
BOOL _scrollAllowed;
UIView * _contentView;
NSMutableArray * _resultsArray;
UIPopoverController * _popoverController;
BOOL _managesContentViewFrame;
}
@dynamic delegate;
@synthesize showAlreadyTokenized = _showAlreadyTokenized;
@synthesize searchSubtitles = _searchSubtitles;
@synthesize forcePickSearchResult = _forcePickSearchResult;
@synthesize tokenField = _tokenField;
@synthesize resultsTable = _resultsTable;
@synthesize contentView = _contentView;
@synthesize separator = _separator;
@synthesize sourceArray = _sourceArray;
@synthesize resultsArray = _resultsArray;
@synthesize searchCompareOptions = _searchCompareOptions;
#pragma mark Init
- (instancetype)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])){
[self setup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])){
[self setup];
}
return self;
}
- (void)setup {
[self setBackgroundColor:[UIColor clearColor]];
[self setDelaysContentTouches:YES];
[self setMultipleTouchEnabled:NO];
_showAlreadyTokenized = NO;
_searchSubtitles = YES;
_scrollAllowed = YES;
_managesContentViewFrame = NO;
_resultsArray = [NSMutableArray array];
_searchCompareOptions = NSCaseInsensitiveSearch;
_tokenField = [[TITokenField alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 42)];
[_tokenField addTarget:self action:@selector(tokenFieldDidBeginEditing:) forControlEvents:UIControlEventEditingDidBegin];
[_tokenField addTarget:self action:@selector(tokenFieldDidEndEditing:) forControlEvents:UIControlEventEditingDidEnd];
[_tokenField addTarget:self action:@selector(tokenFieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];
[_tokenField addTarget:self action:@selector(tokenFieldFrameWillChange:) forControlEvents:(UIControlEvents)TITokenFieldControlEventFrameWillChange];
[_tokenField addTarget:self action:@selector(tokenFieldFrameDidChange:) forControlEvents:(UIControlEvents)TITokenFieldControlEventFrameDidChange];
[_tokenField setDelegate:self];
[self addSubview:_tokenField];
CGFloat tokenFieldBottom = CGRectGetMaxY(_tokenField.frame);
_separator = [[UIView alloc] initWithFrame:CGRectMake(0, tokenFieldBottom, self.bounds.size.width, 1)];
[_separator setBackgroundColor:[UIColor colorWithWhite:0.7 alpha:1]];
[self addSubview:_separator];
// This view is created for convenience, because it resizes and moves with the rest of the subviews.
_contentView = [[UIView alloc] initWithFrame:CGRectMake(0, tokenFieldBottom + 1, self.bounds.size.width,
self.bounds.size.height - tokenFieldBottom - 1)];
[_contentView setBackgroundColor:[UIColor clearColor]];
[self addSubview:_contentView];
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
UITableViewController * tableViewController = [[UITableViewController alloc] initWithStyle:UITableViewStylePlain];
[tableViewController.tableView setDelegate:self];
[tableViewController.tableView setDataSource:self];
[tableViewController setContentSizeForViewInPopover:CGSizeMake(400, 400)];
_resultsTable = tableViewController.tableView;
_popoverController = [[UIPopoverController alloc] initWithContentViewController:tableViewController];
}
else
{
_resultsTable = [[UITableView alloc] initWithFrame:CGRectMake(0, tokenFieldBottom + 1, self.bounds.size.width, 10)];
[_resultsTable setSeparatorColor:[UIColor colorWithWhite:0.85 alpha:1]];
[_resultsTable setBackgroundColor:[UIColor colorWithRed:0.92 green:0.92 blue:0.92 alpha:1]];
[_resultsTable setDelegate:self];
[_resultsTable setDataSource:self];
[_resultsTable setHidden:YES];
[self addSubview:_resultsTable];
_popoverController = nil;
}
[self bringSubviewToFront:_separator];
[self bringSubviewToFront:_tokenField];
[self updateContentSize];
}
#pragma mark Property Overrides
- (BOOL)managesContentViewFrame {
return _managesContentViewFrame;
}
// Setting this property to YES forces the content view to always fully fit inside
// the TITokenFieldView's frame instead of allowing it to extend past the edges,
// in which case the user would have to scroll to be able to see it. This enables
// the use case where the entire contents of the TITokenFieldView do not scroll;
// then a scrollable view can be placed inside the contentView. This, in conjunction
// with setting scrollEnabled to NO on the TITokenFieldView, allow us to build a UI
// where the TITokenField is pinned to the top of the screen while the contents of
// the contentView are scrollable.
- (void)setManagesContentViewFrame:(BOOL)managesContentViewFrame {
_managesContentViewFrame = managesContentViewFrame;
if (managesContentViewFrame) {
[self setNeedsLayout];
}
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
if (_popoverController.popoverVisible){
[_popoverController dismissPopoverAnimated:NO];
[self presentpopoverAtTokenFieldCaretAnimated:NO];
}
if (!_managesContentViewFrame) {
[self calculateViewFrames];
}
[self setNeedsLayout];
}
- (void)setContentOffset:(CGPoint)offset {
[super setContentOffset:offset];
[self setNeedsLayout];
}
- (NSArray *)tokenTitles {
return _tokenField.tokenTitles;
}
// Hide the fact that we internally enable and disable scrolling depending on
// whether the results table is showing. This value should mean, "whether the view
// scrolls in general," not "the view is currently physically scrollable."
- (void)setScrollEnabled:(BOOL)scrollEnabled {
_scrollAllowed = scrollEnabled;
[super setScrollEnabled:scrollEnabled];
}
- (BOOL)isScrollEnabled {
return _scrollAllowed;
}
// We use this internally to set the actual scrolling behaviour - we disable
// scrolling when the results table is visible, and enable scrolling if it's
// not visible *and scrolling is allowed* (as set by setScrollEnabled: above).
- (void)setScrollEnabledIfAllowed:(BOOL)enableScrolling {
[super setScrollEnabled:_scrollAllowed && enableScrolling];
}
- (void)setForcePickSearchResult:(BOOL)forcePickSearchResult
{
_tokenField.forcePickSearchResult = forcePickSearchResult;
_forcePickSearchResult = forcePickSearchResult;
}
#pragma mark Event Handling
- (void)calculateViewFrames {
CGFloat width = self.frame.size.width;
[_separator setFrame:((CGRect){_separator.frame.origin, {width, _separator.bounds.size.height}})];
[_resultsTable setFrame:((CGRect){_resultsTable.frame.origin, {width, _resultsTable.bounds.size.height}})];
[_tokenField setFrame:((CGRect){_tokenField.frame.origin, {width, _tokenField.bounds.size.height}})];
[_contentView setFrame:((CGRect){_contentView.frame.origin, {width, (self.frame.size.height - CGRectGetMaxY(_tokenField.frame) - self.contentInset.top)}})];
}
- (void)layoutSubviews {
[super layoutSubviews];
if (_managesContentViewFrame) {
[self calculateViewFrames];
}
[self updateContentSize];
CGFloat relativeFieldHeight = CGRectGetMaxY(_tokenField.frame) - self.contentOffset.y;
CGFloat newHeight = self.bounds.size.height - relativeFieldHeight;
if (newHeight > -1) [_resultsTable setFrame:((CGRect){_resultsTable.frame.origin, {_resultsTable.bounds.size.width, newHeight}})];
}
- (void)updateContentSize {
[self setContentSize:CGSizeMake(self.bounds.size.width, CGRectGetMaxY(_contentView.frame) + 1)];
}
#pragma mark TableView Methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:resultsTableView:heightForRowAtIndexPath:)]){
return [_tokenField.delegate tokenField:_tokenField resultsTableView:tableView heightForRowAtIndexPath:indexPath];
}
return 44;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:didFinishSearch:)]){
[_tokenField.delegate tokenField:_tokenField didFinishSearch:_resultsArray];
}
return _resultsArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
id representedObject = [_resultsArray objectAtIndex:indexPath.row];
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:resultsTableView:cellForRepresentedObject:)]){
return [_tokenField.delegate tokenField:_tokenField resultsTableView:tableView cellForRepresentedObject:representedObject];
}
static NSString * CellIdentifier = @"ResultsCell";
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSString * subtitle = [self searchResultSubtitleForRepresentedObject:representedObject];
if (!cell) cell = [[UITableViewCell alloc] initWithStyle:(subtitle ? UITableViewCellStyleSubtitle : UITableViewCellStyleDefault) reuseIdentifier:CellIdentifier];
[cell.textLabel setText:[self searchResultStringForRepresentedObject:representedObject]];
[cell.detailTextLabel setText:subtitle];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
id representedObject = [_resultsArray objectAtIndex:indexPath.row];
TIToken * token;
if (self.tokenField.useFlatStyle) {
token = [[TIFlatToken alloc] initWithTitle:[self displayStringForRepresentedObject:representedObject] representedObject:representedObject];
} else {
token = [[TIToken alloc] initWithTitle:[self displayStringForRepresentedObject:representedObject] representedObject:representedObject];
}
[_tokenField addToken:token];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[self setSearchResultsVisible:NO];
}
#pragma mark TextField Methods
- (void)tokenFieldDidBeginEditing:(TITokenField *)field {
[_resultsArray removeAllObjects];
[_resultsTable reloadData];
}
- (void)tokenFieldDidEndEditing:(TITokenField *)field {
[self tokenFieldDidBeginEditing:field];
}
- (void)tokenFieldTextDidChange:(TITokenField *)field {
[self resultsForSearchString:_tokenField.text];
if (_forcePickSearchResult) {
[self setSearchResultsVisible:YES];
} else {
[self setSearchResultsVisible:(_resultsArray.count > 0)];
}
}
- (void)tokenFieldFrameWillChange:(TITokenField *)field {
CGFloat tokenFieldBottom = CGRectGetMaxY(_tokenField.frame);
[_separator setFrame:((CGRect){{_separator.frame.origin.x, tokenFieldBottom}, _separator.bounds.size})];
[_resultsTable setFrame:((CGRect){{_resultsTable.frame.origin.x, (tokenFieldBottom + 1)}, _resultsTable.bounds.size})];
[_contentView setFrame:((CGRect){{_contentView.frame.origin.x, (tokenFieldBottom + 1)}, _contentView.bounds.size})];
}
- (void)tokenFieldFrameDidChange:(TITokenField *)field {
[self updateContentSize];
}
#pragma mark Results Methods
- (NSString *)displayStringForRepresentedObject:(id)object {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:displayStringForRepresentedObject:)]){
return [_tokenField.delegate tokenField:_tokenField displayStringForRepresentedObject:object];
}
if ([object isKindOfClass:[NSString class]]){
return (NSString *)object;
}
return [NSString stringWithFormat:@"%@", object];
}
- (NSString *)searchResultStringForRepresentedObject:(id)object {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:searchResultStringForRepresentedObject:)]){
return [_tokenField.delegate tokenField:_tokenField searchResultStringForRepresentedObject:object];
}
return [self displayStringForRepresentedObject:object];
}
- (NSString *)searchResultSubtitleForRepresentedObject:(id)object {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:searchResultSubtitleForRepresentedObject:)]){
return [_tokenField.delegate tokenField:_tokenField searchResultSubtitleForRepresentedObject:object];
}
return nil;
}
- (void)setSearchResultsVisible:(BOOL)visible {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
if (visible) [self presentpopoverAtTokenFieldCaretAnimated:YES];
else [_popoverController dismissPopoverAnimated:YES];
}
else
{
[_resultsTable setHidden:!visible];
[_tokenField setResultsModeEnabled:visible];
}
}
- (void)resultsForSearchString:(NSString *)searchString {
// The brute force searching method.
// Takes the input string and compares it against everything in the source array.
// If the source is massive, this could take some time.
// You could always subclass and override this if needed or do it on a background thread.
// GCD would be great for that.
[_resultsArray removeAllObjects];
[_resultsTable reloadData];
searchString = [searchString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
//TRIBEHR: The line below corrects the following bug: Employee Names Missing in Give Kudos https://www.pivotaltracker.com/story/show/53980813
// We didn't fully understand what the issue was. The same search string would be passed through here twice in separate occasions separated by
// a visit to another screen - the View Kudos page, more specifically - but while in the first pass the line above would trim it of extraneous characters
// (namely the Zero Width Space character, \u200B), in the second pass this wouldn't happen.
searchString = [searchString stringByReplacingOccurrencesOfString:@"\u200B" withString:@""];
if (searchString.length || _forcePickSearchResult){
[_sourceArray enumerateObjectsUsingBlock:^(id sourceObject, NSUInteger idx, BOOL *stop){
NSString * query = [self searchResultStringForRepresentedObject:sourceObject];
NSString * querySubtitle = [self searchResultSubtitleForRepresentedObject:sourceObject];
if (!querySubtitle || !_searchSubtitles) querySubtitle = @"";
if ([query rangeOfString:searchString options:self.searchCompareOptions].location != NSNotFound ||
[querySubtitle rangeOfString:searchString options:self.searchCompareOptions].location != NSNotFound ||
(_forcePickSearchResult && searchString.length == 0)){
__block BOOL shouldAdd = ![_resultsArray containsObject:sourceObject];
if (shouldAdd && !_showAlreadyTokenized){
[_tokenField.tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *secondStop){
if ([token.representedObject isEqual:sourceObject]){
shouldAdd = NO;
*secondStop = YES;
}
}];
}
if (shouldAdd) [_resultsArray addObject:sourceObject];
}
}];
}
if (_resultsArray.count > 0) {
[_resultsArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[self searchResultStringForRepresentedObject:obj1] localizedCaseInsensitiveCompare:[self searchResultStringForRepresentedObject:obj2]];
}];
[_resultsTable reloadData];
}
}
- (void)presentpopoverAtTokenFieldCaretAnimated:(BOOL)animated {
UITextPosition * position = [_tokenField positionFromPosition:_tokenField.beginningOfDocument offset:2];
[_popoverController presentPopoverFromRect:[_tokenField caretRectForPosition:position] inView:_tokenField
permittedArrowDirections:UIPopoverArrowDirectionUp animated:animated];
}
#pragma mark Other
- (NSString *)description {
return [NSString stringWithFormat:@"<TITokenFieldView %p; Token count = %d>", self, self.tokenTitles.count];
}
- (void)dealloc {
[self setDelegate:nil];
}
@end
//==========================================================
#pragma mark - TITokenField -
//==========================================================
NSString * const kTextEmpty = @"\u200B"; // Zero-Width Space
NSString * const kTextHidden = @"\u200D"; // Zero-Width Joiner
@interface TITokenFieldInternalDelegate ()
@property (nonatomic, weak) id <UITextFieldDelegate> delegate;
@property (nonatomic, weak) TITokenField * tokenField;
@end
@interface TITokenField ()
@property (nonatomic, readonly) CGFloat leftViewWidth;
@property (nonatomic, readonly) CGFloat rightViewWidth;
@property (weak, nonatomic, readonly) UIScrollView * scrollView;
@end
@interface TITokenField (Private)
- (void)setup;
- (CGFloat)layoutTokensInternal;
@end
@implementation TITokenField {
id __weak delegate;
TITokenFieldInternalDelegate * _internalDelegate;
NSMutableArray * _tokens;
CGPoint _tokenCaret;
UILabel * _placeHolderLabel;
}
@synthesize delegate = delegate;
@synthesize editable = _editable;
@synthesize resultsModeEnabled = _resultsModeEnabled;
@synthesize removesTokensOnEndEditing = _removesTokensOnEndEditing;
@synthesize numberOfLines = _numberOfLines;
@synthesize selectedToken = _selectedToken;
@synthesize tokenizingCharacters = _tokenizingCharacters;
@synthesize forcePickSearchResult = _forcePickSearchResult;
#pragma mark Init
- (instancetype)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])){
[self setup];
}
return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])){
[self setup];
}
return self;
}
- (void)setup {
self.useFlatStyle = isIOS7OrGreater();
[self setBorderStyle:UITextBorderStyleNone];
[self setFont:[UIFont systemFontOfSize:14]];
[self setBackgroundColor:[UIColor whiteColor]];
[self setAutocorrectionType:UITextAutocorrectionTypeNo];
[self setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[self setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
[self addTarget:self action:@selector(didBeginEditing) forControlEvents:UIControlEventEditingDidBegin];
[self addTarget:self action:@selector(didEndEditing) forControlEvents:UIControlEventEditingDidEnd];
[self addTarget:self action:@selector(didChangeText) forControlEvents:UIControlEventEditingChanged];
[self.layer setShadowColor:[[UIColor blackColor] CGColor]];
[self.layer setShadowOpacity:0.6];
[self.layer setShadowRadius:12];
[self setPromptText:@"To:"];
[self setText:kTextEmpty];
_internalDelegate = [[TITokenFieldInternalDelegate alloc] init];
[_internalDelegate setTokenField:self];
[super setDelegate:_internalDelegate];
_tokens = [NSMutableArray array];
_editable = YES;
_removesTokensOnEndEditing = YES;
_tokenizingCharacters = [NSCharacterSet characterSetWithCharactersInString:@","];
}
#pragma mark Property Overrides
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
[self.layer setShadowPath:[[UIBezierPath bezierPathWithRect:self.bounds] CGPath]];
[self layoutTokensAnimated:NO];
}
- (void)setText:(NSString *)text {
[super setText:(text.length == 0 ? kTextEmpty : text)];
}
- (void)setFont:(UIFont *)font {
[super setFont:font];
if ([self.leftView isKindOfClass:[UILabel class]]){
[self setPromptText:((UILabel *)self.leftView).text];
}
}
- (void)setDelegate:(id<TITokenFieldDelegate>)del {
delegate = del;
[_internalDelegate setDelegate:delegate];
}
- (NSArray *)tokens {
return [_tokens copy];
}
- (NSArray *)tokenTitles {
NSMutableArray * titles = [NSMutableArray array];
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){
if (token.title) [titles addObject:token.title];
}];
return titles;
}
- (NSArray *)tokenObjects {
NSMutableArray * objects = [NSMutableArray array];
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){
if (token.representedObject) [objects addObject:token.representedObject];
else if (token.title) [objects addObject:token.title];
}];
return objects;
}
- (UIScrollView *)scrollView {
return ([self.superview isKindOfClass:[UIScrollView class]] ? (UIScrollView *)self.superview : nil);
}
#pragma mark Event Handling
- (BOOL)becomeFirstResponder {
return (_editable ? [super becomeFirstResponder] : NO);
}
- (void)didBeginEditing {
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){[self addToken:token];}];
}
- (void)didEndEditing {
[_selectedToken setSelected:NO];
_selectedToken = nil;
[self tokenizeText];
if (_removesTokensOnEndEditing){
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){[token removeFromSuperview];}];
NSString * untokenized = kTextEmpty;
if (_tokens.count){
NSMutableArray * titles = [NSMutableArray array];
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){
if (token.title) [titles addObject:token.title];
}];
untokenized = [self.tokenTitles componentsJoinedByString:@", "];
CGSize untokSize = [untokenized sizeWithFont:[UIFont systemFontOfSize:14]];
CGFloat availableWidth = self.bounds.size.width - self.leftView.bounds.size.width - self.rightView.bounds.size.width;
if (_tokens.count > 1 && untokSize.width > availableWidth){
untokenized = [NSString stringWithFormat:@"%d recipients", titles.count];
}
}
[self setText:untokenized];
}
[self setResultsModeEnabled:NO];
if (_tokens.count < 1 && self.forcePickSearchResult) {
[self becomeFirstResponder];
}
}
- (void)didChangeText {
if (!self.text.length) {
[self setText:kTextEmpty];
[_placeHolderLabel setHidden:NO];
} else [_placeHolderLabel setHidden:YES];
}
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
// Stop the cut, copy, select and selectAll appearing when the field is 'empty'.
if (action == @selector(cut:) || action == @selector(copy:) || action == @selector(select:) || action == @selector(selectAll:))
return ![self.text isEqualToString:kTextEmpty];
return [super canPerformAction:action withSender:sender];
}
- (BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event {
if (_selectedToken && touch.view == self) [self deselectSelectedToken];
return [super beginTrackingWithTouch:touch withEvent:event];
}
#pragma mark Token Handling
- (TIToken *)addTokenWithTitle:(NSString *)title {
return [self addTokenWithTitle:title representedObject:nil];
}
- (TIToken *)addTokenWithTitle:(NSString *)title representedObject:(id)object {
if (title.length){
TIToken* token;
if (self.useFlatStyle) {
token = [[TIFlatToken alloc] initWithTitle:title representedObject:object font:self.font];
} else {
token = [[TIToken alloc] initWithTitle:title representedObject:object font:self.font];
}
[self addToken:token];
return token;
}
return nil;
}
- (void)addToken:(TIToken *)token {
BOOL shouldAdd = YES;
if ([delegate respondsToSelector:@selector(tokenField:willAddToken:)]){
shouldAdd = [delegate tokenField:self willAddToken:token];
}
if (shouldAdd){
[self becomeFirstResponder];
[token addTarget:self action:@selector(tokenTouchDown:) forControlEvents:UIControlEventTouchDown];
[token addTarget:self action:@selector(tokenTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:token];
if (![_tokens containsObject:token]) {
[_tokens addObject:token];
if ([delegate respondsToSelector:@selector(tokenField:didAddToken:)]){
[delegate tokenField:self didAddToken:token];
}
[_placeHolderLabel setHidden:YES];
}
[self setResultsModeEnabled:NO];
[self deselectSelectedToken];
}
}
- (void)removeToken:(TIToken *)token {
if (token == _selectedToken) [self deselectSelectedToken];
BOOL shouldRemove = YES;
if ([delegate respondsToSelector:@selector(tokenField:willRemoveToken:)]){
shouldRemove = [delegate tokenField:self willRemoveToken:token];
}
if (shouldRemove){
[token removeFromSuperview];
[_tokens removeObject:token];
if ([delegate respondsToSelector:@selector(tokenField:didRemoveToken:)]){
[delegate tokenField:self didRemoveToken:token];
}
[self setResultsModeEnabled:_forcePickSearchResult];
}
}
- (void)removeAllTokens {
[_tokens enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop) {
[self removeToken:token];
}];
[self setText:@""];
}
- (void)selectToken:(TIToken *)token {
[self deselectSelectedToken];
_selectedToken = token;
[_selectedToken setSelected:YES];
[self becomeFirstResponder];
[self setText:kTextHidden];
}
- (void)deselectSelectedToken {
[_selectedToken setSelected:NO];
_selectedToken = nil;
[self setText:kTextEmpty];
}
- (void)tokenizeText {
__block BOOL textChanged = NO;
if (![self.text isEqualToString:kTextEmpty] && ![self.text isEqualToString:kTextHidden] && !_forcePickSearchResult){
[[self.text componentsSeparatedByCharactersInSet:_tokenizingCharacters] enumerateObjectsUsingBlock:^(NSString * component, NSUInteger idx, BOOL *stop){
[self addTokenWithTitle:[component stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
textChanged = YES;
}];
}
if (textChanged) [self sendActionsForControlEvents:UIControlEventEditingChanged];
}
- (void)tokenTouchDown:(TIToken *)token {
if (_selectedToken != token){
[_selectedToken setSelected:NO];
_selectedToken = nil;
}
}
- (void)tokenTouchUpInside:(TIToken *)token {
if (_editable) [self selectToken:token];
}
- (CGFloat)layoutTokensInternal {
CGFloat topMargin = floor(self.font.lineHeight * 4 / 7);
CGFloat leftMargin = self.leftViewWidth + 12;
CGFloat hPadding = 8;
CGFloat rightMargin = self.rightViewWidth + hPadding;
CGFloat lineHeight = ceil(self.font.lineHeight + topMargin + 5);
_numberOfLines = 1;
_tokenCaret = (CGPoint){leftMargin, (topMargin - 1)};
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){
[token setFont:self.font];
[token setMaxWidth:(self.bounds.size.width - rightMargin - (_numberOfLines > 1 ? hPadding : leftMargin))];
if (token.superview){
if (_tokenCaret.x + token.bounds.size.width + rightMargin > self.bounds.size.width){
_numberOfLines++;
_tokenCaret.x = (_numberOfLines > 1 ? hPadding : leftMargin);
_tokenCaret.y += lineHeight;
}
[token setFrame:(CGRect){_tokenCaret, token.bounds.size}];
_tokenCaret.x += token.bounds.size.width + 4;
if (self.bounds.size.width - _tokenCaret.x - rightMargin < 50){
_numberOfLines++;
_tokenCaret.x = (_numberOfLines > 1 ? hPadding : leftMargin);
_tokenCaret.y += lineHeight;
}
}
}];
return _tokenCaret.y + lineHeight;
}
#pragma mark View Handlers
- (void)layoutTokensAnimated:(BOOL)animated {
CGFloat newHeight = [self layoutTokensInternal];
if (self.bounds.size.height != newHeight){
// Animating this seems to invoke the triple-tap-delete-key-loop-problem-thing™
[UIView animateWithDuration:(animated ? 0.3 : 0) animations:^{
[self setFrame:((CGRect){self.frame.origin, {self.bounds.size.width, newHeight}})];
[self sendActionsForControlEvents:(UIControlEvents)TITokenFieldControlEventFrameWillChange];
} completion:^(BOOL complete){
if (complete) [self sendActionsForControlEvents:(UIControlEvents)TITokenFieldControlEventFrameDidChange];
}];
}
}
- (void)setResultsModeEnabled:(BOOL)flag {
[self setResultsModeEnabled:flag animated:YES];
}
- (void)setResultsModeEnabled:(BOOL)flag animated:(BOOL)animated {
[self layoutTokensAnimated:animated];
if (_resultsModeEnabled != flag){
//Hide / show the shadow
[self.layer setMasksToBounds:!flag];
UIEdgeInsets contentInsets = UIEdgeInsetsMake(0, 0, 0, 0);
UIScrollView * scrollView = self.scrollView;
if ([scrollView isKindOfClass:TITokenFieldView.class]) {
TITokenFieldView* container = (TITokenFieldView*)scrollView;
[container setScrollEnabledIfAllowed:!flag];
contentInsets = container.contentInset;
} else {
[scrollView setScrollsToTop:!flag];
[scrollView setScrollEnabled:!flag];
}
CGFloat offset = ((_numberOfLines == 1 || !flag) ? 0 : _tokenCaret.y - floor(self.font.lineHeight * 4 / 7) + 1);
[scrollView setContentOffset:CGPointMake(0, self.frame.origin.y + offset - contentInsets.top) animated:animated];
}
_resultsModeEnabled = flag;
}
#pragma mark Left / Right view stuff
- (void)setPromptText:(NSString *)text {
if (text){
UILabel * label = (UILabel *)self.leftView;
if (!label || ![label isKindOfClass:[UILabel class]]){
label = [[UILabel alloc] initWithFrame:CGRectZero];
[label setTextColor:[UIColor colorWithWhite:0.5 alpha:1]];
[self setLeftView:label];
[self setLeftViewMode:UITextFieldViewModeAlways];
}
[label setText:text];
[label setFont:[UIFont systemFontOfSize:(self.font.pointSize + 1)]];
[label sizeToFit];
}
else
{
[self setLeftView:nil];
}
[self layoutTokensAnimated:YES];
}
- (void)setPlaceholder:(NSString *)placeholder {
if (placeholder){
UILabel * label = _placeHolderLabel;
if (!label || ![label isKindOfClass:[UILabel class]]){
label = [[UILabel alloc] initWithFrame:CGRectMake(_tokenCaret.x + 3, _tokenCaret.y + 2, self.rightView.bounds.size.width, self.rightView.bounds.size.height)];
[label setTextColor:[UIColor colorWithWhite:0.75 alpha:1]];
_placeHolderLabel = label;
[self addSubview: _placeHolderLabel];
}
[label setText:placeholder];
[label setFont:[UIFont systemFontOfSize:(self.font.pointSize + 1)]];
[label sizeToFit];
}
else
{
[_placeHolderLabel removeFromSuperview];
_placeHolderLabel = nil;
}
[self layoutTokensAnimated:YES];
}
#pragma mark Layout
- (CGRect)textRectForBounds:(CGRect)bounds {
if ([self.text isEqualToString:kTextHidden]) return CGRectMake(0, -20, 0, 0);
CGRect frame = CGRectOffset(bounds, _tokenCaret.x + 2, _tokenCaret.y + 3);
frame.size.width -= (_tokenCaret.x + self.rightViewWidth + 10);
return frame;
}
- (CGRect)editingRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)placeholderRectForBounds:(CGRect)bounds {
return [self textRectForBounds:bounds];
}
- (CGRect)leftViewRectForBounds:(CGRect)bounds {
return ((CGRect){{8, ceilf(self.font.lineHeight * 4 / 7)}, self.leftView.bounds.size});
}
- (CGRect)rightViewRectForBounds:(CGRect)bounds {
return ((CGRect){{floor(bounds.size.width - self.rightView.bounds.size.width - 6),
floor(bounds.size.height - self.rightView.bounds.size.height - 6)}, self.rightView.bounds.size});
}
- (CGFloat)leftViewWidth {
if (self.leftViewMode == UITextFieldViewModeNever ||
(self.leftViewMode == UITextFieldViewModeUnlessEditing && self.editing) ||
(self.leftViewMode == UITextFieldViewModeWhileEditing && !self.editing)) return 0;
return self.leftView.bounds.size.width;
}
- (CGFloat)rightViewWidth {
if (self.rightViewMode == UITextFieldViewModeNever ||
(self.rightViewMode == UITextFieldViewModeUnlessEditing && self.editing) ||
(self.rightViewMode == UITextFieldViewModeWhileEditing && !self.editing)) return 0;
return self.rightView.bounds.size.width;
}
#pragma mark Other
- (NSString *)description {
return [NSString stringWithFormat:@"<TITokenField %p; prompt = \"%@\">", self, ((UILabel *)self.leftView).text];
}
- (void)dealloc {
[self setDelegate:nil];
}
@end
//==========================================================
#pragma mark - TITokenFieldInternalDelegate -
//==========================================================
@implementation TITokenFieldInternalDelegate
@synthesize delegate = _delegate;
@synthesize tokenField = _tokenField;
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if ([_delegate respondsToSelector:@selector(textFieldShouldBeginEditing:)]){
return [_delegate textFieldShouldBeginEditing:textField];
}
return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
if ([_delegate respondsToSelector:@selector(textFieldDidBeginEditing:)]){
[_delegate textFieldDidBeginEditing:textField];