@@ -17,6 +17,9 @@ @interface ViewController ()
1717@end
1818
1919@implementation ViewController
20+ {
21+ RFKeyboardToolbar *keyboardToolbar;
22+ }
2023
2124- (void )viewDidLoad
2225{
@@ -32,9 +35,41 @@ - (void)viewDidLoad
3235 [_textView insertText: @" You pressed a button!" ];
3336 } forControlEvents: UIControlEventTouchUpInside];
3437
35- _textView.inputAccessoryView = [RFKeyboardToolbar toolbarViewWithButtons: @[exampleButton]];
36-
38+ keyboardToolbar = [RFKeyboardToolbar toolbarViewWithButtons: @[exampleButton]];
39+ _textView.inputAccessoryView = keyboardToolbar;
40+ _textView.delegate = self;
41+
3742 [self .view addSubview: _textView];
3843}
3944
45+ - (void )textViewDidChange : (UITextView *)textView
46+ {
47+ // get unique words in field
48+ NSSet *words = [NSSet setWithArray: [textView.text.lowercaseString componentsSeparatedByCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet ]]];
49+
50+ // dictionary of existing words => buttons
51+ NSDictionary *oldButtons = [NSDictionary dictionaryWithObjects: keyboardToolbar.buttons forKeys: [keyboardToolbar.buttons valueForKey: @" title" ]];
52+
53+ // create new buttons
54+ NSMutableArray *newButtons = [NSMutableArray arrayWithCapacity: words.count];
55+ for (__strong NSString *word in words) {
56+ word = [word stringByTrimmingCharactersInSet: [NSCharacterSet punctuationCharacterSet ]];
57+ if (word.length == 0 ) continue ;
58+ // create or reuse button
59+ RFToolbarButton *button = oldButtons[word];
60+ if (button == nil ) {
61+ button = [RFToolbarButton buttonWithTitle: word];
62+ [button addEventHandler: ^{
63+ [_textView insertText: word];
64+ } forControlEvents: UIControlEventTouchUpInside];
65+ }
66+ [newButtons addObject: button];
67+ }
68+
69+ [newButtons sortUsingComparator: ^NSComparisonResult (id obj1, id obj2) {
70+ return [[obj1 title ] compare: [obj2 title ]];
71+ }];
72+ [keyboardToolbar setButtons: newButtons animated: YES ];
73+ }
74+
4075@end
0 commit comments