-
Notifications
You must be signed in to change notification settings - Fork 171
/
TITokenField.m
1466 lines (1109 loc) · 47.5 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>
@interface TITokenField ()
@property (nonatomic, assign) BOOL forcePickSearchResult;
@property (nonatomic, assign) BOOL alwaysShowSearchResult;
@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;
@end
@implementation TITokenFieldView {
UIView * _contentView;
NSMutableArray * _resultsArray;
UIPopoverController * _popoverController;
}
@dynamic delegate;
@synthesize showAlreadyTokenized = _showAlreadyTokenized;
@synthesize searchSubtitles = _searchSubtitles;
@synthesize subtitleIsPhoneNumber = _subtitleIsPhoneNumber;
@synthesize forcePickSearchResult = _forcePickSearchResult;
@synthesize alwaysShowSearchResult = _alwaysShowSearchResult;
@synthesize shouldSortResults = _shouldSortResults;
@synthesize shouldSearchInBackground = _shouldSearchInBackground;
@synthesize shouldAlwaysShowSeparator = _shouldAlwaysShowSeparator;
@synthesize permittedArrowDirections = _permittedArrowDirections;
@synthesize tokenField = _tokenField;
@synthesize resultsTable = _resultsTable;
@synthesize contentView = _contentView;
@synthesize separator = _separator;
@synthesize tableHeader = _tableHeader;
@synthesize sourceArray = _sourceArray;
#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:NO];
[self setMultipleTouchEnabled:NO];
_showAlreadyTokenized = NO;
_searchSubtitles = YES;
_subtitleIsPhoneNumber = NO;
_forcePickSearchResult = NO;
_alwaysShowSearchResult = NO;
_shouldSortResults = YES;
_shouldSearchInBackground = NO;
_shouldAlwaysShowSeparator = YES;
_permittedArrowDirections = UIPopoverArrowDirectionUp;
_resultsArray = [NSMutableArray array];
_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]];
_tableHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 1)];
[_tableHeader 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;
}
if (_shouldAlwaysShowSeparator) {
[self bringSubviewToFront:_separator];
} else {
_separator.hidden = YES;
_resultsTable.tableHeaderView = _tableHeader;
}
[self bringSubviewToFront:_tokenField];
[self updateContentSize];
}
#pragma mark Property Overrides
- (void) setChildFrames:(CGRect)frame {
CGFloat width = 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}})];
[_contentView setFrame:((CGRect){_contentView.frame.origin, {width, (frame.size.height - CGRectGetMaxY(_tokenField.frame))}})];
[_tokenField setFrame:((CGRect){_tokenField.frame.origin, {width, _tokenField.bounds.size.height}})];
}
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
[self setChildFrames:frame];
if (_popoverController.popoverVisible){
[_popoverController dismissPopoverAnimated:NO];
[self presentpopoverAtTokenFieldCaretAnimated:NO];
}
[self updateContentSize];
[self setNeedsLayout];
}
- (void)setContentOffset:(CGPoint)offset {
[super setContentOffset:offset];
[self setNeedsLayout];
}
- (NSArray *)tokenTitles {
return _tokenField.tokenTitles;
}
- (void)setForcePickSearchResult:(BOOL)forcePickSearchResult
{
_tokenField.forcePickSearchResult = forcePickSearchResult;
_forcePickSearchResult = forcePickSearchResult;
}
- (void)setAlwaysShowSearchResult:(BOOL)alwaysShowSearchResult
{
_tokenField.alwaysShowSearchResult = alwaysShowSearchResult;
_alwaysShowSearchResult = alwaysShowSearchResult;
if (_alwaysShowSearchResult) [self resultsForSearchString:_tokenField.text];
}
- (void) setShouldAlwaysShowSeparator:(BOOL)shouldAlwaysShowSeparator
{
_shouldAlwaysShowSeparator = shouldAlwaysShowSeparator;
if (_shouldAlwaysShowSeparator) {
_resultsTable.tableHeaderView = nil;
_separator.hidden = NO;
[self bringSubviewToFront:_separator];
} else {
_separator.hidden = YES;
_resultsTable.tableHeaderView = _tableHeader;
}
}
#pragma mark Event Handling
- (void)layoutSubviews {
[super layoutSubviews];
[self setChildFrames:self.frame];
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)];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (BOOL)becomeFirstResponder {
return [_tokenField becomeFirstResponder];
}
- (BOOL)resignFirstResponder {
return [_tokenField resignFirstResponder];
}
#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.imageView setImage:[self searchResultImageForRepresentedObject:representedObject]];
[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 = [[TIToken alloc] initWithTitle:[self displayStringForRepresentedObject:representedObject] representedObject:representedObject];
[_tokenField addToken:token];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (!_alwaysShowSearchResult) [self setSearchResultsVisible:NO];
}
#pragma mark TextField Methods
- (void)tokenFieldDidBeginEditing:(TITokenField *)field {
if (!_alwaysShowSearchResult) [_resultsArray removeAllObjects];
[_resultsTable reloadData];
}
- (void)tokenFieldDidEndEditing:(TITokenField *)field {
[self tokenFieldDidBeginEditing:field];
}
- (void)tokenFieldTextDidChange:(TITokenField *)field {
[self resultsForSearchString:_tokenField.text];
if (_forcePickSearchResult || _alwaysShowSearchResult) [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;
}
- (UIImage *)searchResultImageForRepresentedObject:(id)object {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:searchResultImageForRepresentedObject:)]) {
return [_tokenField.delegate tokenField:_tokenField searchResultImageForRepresentedObject: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]];
if (searchString.length || _forcePickSearchResult || _alwaysShowSearchResult){
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:shouldUseCustomSearchForSearchString:)] && [_tokenField.delegate tokenField:_tokenField shouldUseCustomSearchForSearchString:searchString]) {
if ([_tokenField.delegate respondsToSelector:@selector(tokenField:performCustomSearchForSearchString:withCompletionHandler:)]) {
[_tokenField.delegate tokenField:_tokenField performCustomSearchForSearchString:searchString withCompletionHandler:^(NSArray *results) {
[self searchDidFinish:results];
}];
}
} else {
if (_shouldSearchInBackground) {
[self performSelectorInBackground:@selector(performSearch:) withObject:searchString];
} else {
[self performSearch:searchString];
}
}
}
}
- (void) performSearch:(NSString *)searchString {
NSMutableArray * resultsToAdd = [[NSMutableArray alloc] init];
[_sourceArray enumerateObjectsUsingBlock:^(id sourceObject, NSUInteger idx, BOOL *stop){
NSString * query = [self searchResultStringForRepresentedObject:sourceObject];
NSString * querySubtitle = [self searchResultSubtitleForRepresentedObject:sourceObject];
if (!querySubtitle || !self->_searchSubtitles) {
querySubtitle = @"";
} else if (self->_subtitleIsPhoneNumber) {
querySubtitle = [querySubtitle stringByReplacingOccurrencesOfString:@" " withString:@""];
}
if ([query rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound ||
[querySubtitle rangeOfString:searchString options:NSCaseInsensitiveSearch].location != NSNotFound ||
(self->_forcePickSearchResult && searchString.length == 0) ||
(self->_alwaysShowSearchResult && searchString.length == 0)){
__block BOOL shouldAdd = ![resultsToAdd containsObject:sourceObject];
if (shouldAdd && !self->_showAlreadyTokenized){
[self->_tokenField.tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *secondStop){
if ([token.representedObject isEqual:sourceObject]){
shouldAdd = NO;
*secondStop = YES;
}
}];
}
if (shouldAdd) [resultsToAdd addObject:sourceObject];
}
}];
[self searchDidFinish:resultsToAdd];
}
- (void)searchDidFinish:(NSArray *)results
{
[_resultsArray addObjectsFromArray:results];
if (_resultsArray.count > 0) {
if (_shouldSortResults) {
[_resultsArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [[self searchResultStringForRepresentedObject:obj1] localizedCaseInsensitiveCompare:[self searchResultStringForRepresentedObject:obj2]];
}];
}
[self performSelectorOnMainThread:@selector(reloadResultsTable) withObject:nil waitUntilDone:YES];
}
}
-(void) reloadResultsTable {
[_resultsTable setHidden:NO];
[_resultsTable reloadData];
}
- (void)presentpopoverAtTokenFieldCaretAnimated:(BOOL)animated {
UITextPosition * position = [_tokenField positionFromPosition:_tokenField.beginningOfDocument offset:2];
[_popoverController presentPopoverFromRect:[_tokenField caretRectForPosition:position]
inView:_tokenField
permittedArrowDirections:[self permittedArrowDirections]
animated:animated];
}
#pragma mark Other
- (NSString *)description {
return [NSString stringWithFormat:@"<TITokenFieldView %p; Token count = %lu>", self, (unsigned long)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 showShadow = _showShadow;
@synthesize resultsModeEnabled = _resultsModeEnabled;
@synthesize removesTokensOnEndEditing = _removesTokensOnEndEditing;
@synthesize numberOfLines = _numberOfLines;
@synthesize selectedToken = _selectedToken;
@synthesize tokenizingCharacters = _tokenizingCharacters;
@synthesize forcePickSearchResult = _forcePickSearchResult;
@synthesize alwaysShowSearchResult = _alwaysShowSearchResult;
#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 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 setPromptText:@"To:"];
[self setText:kTextEmpty];
self.promptColor = [UIColor colorWithWhite:0.5 alpha:1];
_internalDelegate = [[TITokenFieldInternalDelegate alloc] init];
[_internalDelegate setTokenField:self];
[super setDelegate:_internalDelegate];
[self setShowShadow:YES];
_tokens = [NSMutableArray array];
_editable = YES;
_removesTokensOnEndEditing = YES;
_tokenizingCharacters = [NSCharacterSet characterSetWithCharactersInString:@","];
_tokenLimit = -1;
}
#pragma mark Property Overrides
- (void)setFrame:(CGRect)frame {
[super setFrame:frame];
[self.layer setShadowPath:[[UIBezierPath bezierPathWithRect:self.bounds] CGPath]];
[self layoutTokensAnimated:NO];
}
- (void)setShowShadow:(BOOL)showShadow {
_showShadow = showShadow;
if (showShadow) {
[self.layer setShadowColor:[[UIColor blackColor] CGColor]];
[self.layer setShadowOpacity:0.6];
[self.layer setShadowRadius:12];
} else {
[self.layer setShadowColor:[[UIColor clearColor] CGColor]];
}
}
- (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 {
if (_removesTokensOnEndEditing) {
[_tokens enumerateObjectsUsingBlock:^(TIToken * token, NSUInteger idx, BOOL *stop){[self addTokenToView: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){
NSArray * titles = self.tokenTitles;
untokenized = [titles componentsJoinedByString:@", "];
CGSize untokSize = [untokenized sizeWithAttributes:@{NSFontAttributeName: [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:@"%lu recipients", (unsigned long)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];
[self showOrHidePlaceHolderLabel];
}
- (void) showOrHidePlaceHolderLabel {
[_placeHolderLabel setHidden:!(([self.text isEqualToString:kTextEmpty]) && !_tokens.count)];
}
- (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 = [[TIToken alloc] initWithTitle:title representedObject:object font:self.font];
[self addToken:token];
return token;
}
return nil;
}
- (void)addTokensWithTitleList:(NSString *)titleList {
if ([titleList length] > 0) {
self.text = titleList;
[self tokenizeText];
}
}
- (void)addTokensWithTitleArray:(NSArray *)titleArray {
for (NSString *title in titleArray) {
[self addTokenWithTitle:title];
}
}
- (void)addToken:(TIToken *)token {
BOOL shouldAdd = YES;
if ([delegate respondsToSelector:@selector(tokenField:willAddToken:)]){
shouldAdd = [delegate tokenField:self willAddToken:token];
}
if (shouldAdd){
//[self becomeFirstResponder];
if (![_tokens containsObject:token]) {
[_tokens addObject:token];
if ([delegate respondsToSelector:@selector(tokenField:didAddToken:)]){
[delegate tokenField:self didAddToken:token];
}
}
[self addTokenToView:token];
}
}
- (void) addTokenToView:(TIToken *)token
{
[token addTarget:self action:@selector(tokenTouchDown:) forControlEvents:UIControlEventTouchDown];
[token addTarget:self action:@selector(tokenTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:token];
[self layoutTokensAnimated:YES];
[self showOrHidePlaceHolderLabel];
[self setResultsModeEnabled:_alwaysShowSearchResult];
[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];
[self layoutTokensAnimated:YES];
if ([delegate respondsToSelector:@selector(tokenField:didRemoveToken:)]){
[delegate tokenField:self didRemoveToken:token];
}
[self showOrHidePlaceHolderLabel];
[self setResultsModeEnabled:_forcePickSearchResult || _alwaysShowSearchResult];
}
}
- (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 = ceilf(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 - (self->_numberOfLines > 1 ? hPadding : leftMargin))];
if (token.superview){
if (self->_tokenCaret.x + token.bounds.size.width + rightMargin > self.bounds.size.width){
self->_numberOfLines++;
self->_tokenCaret.x = (self->_numberOfLines > 1 ? hPadding : leftMargin);
self->_tokenCaret.y += lineHeight;
}
[token setFrame:(CGRect){self->_tokenCaret, token.bounds.size}];
self->_tokenCaret.x += token.bounds.size.width + 4;
if (self.bounds.size.width - self->_tokenCaret.x - rightMargin < 50){
self->_numberOfLines++;
self->_tokenCaret.x = (self->_numberOfLines > 1 ? hPadding : leftMargin);
self->_tokenCaret.y += lineHeight;
}
}
}];
return ceilf(_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 && _editable ? 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];
UIScrollView * scrollView = self.scrollView;
[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) animated:animated];
}
_resultsModeEnabled = flag;
}
#pragma mark Left / Right view stuff
- (void)setPromptText:(NSString *)text {
_promptText = text;
if (text){
UILabel * label = (UILabel *)self.leftView;
if (!label || ![label isKindOfClass:[UILabel class]]){
label = [[UILabel alloc] initWithFrame:CGRectZero];
[self setLeftView:label];
[self setLeftViewMode:UITextFieldViewModeAlways];
}
[label setTextColor:_promptColor];
[label setText:text];
[label setFont:[UIFont systemFontOfSize:(self.font.pointSize + 1)]];
[label sizeToFit];
}
else
{
[self setLeftView:nil];
}
[self layoutTokensAnimated:YES];
}
- (void)setPromptColor:(UIColor *)promptColor
{
_promptColor = promptColor;
[self setPromptText:_promptText];
}
- (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){{bounds.size.width - self.rightView.bounds.size.width - 6,
bounds.size.height - self.rightView.bounds.size.height - 6}, self.rightView.bounds.size});
}