Skip to content
This repository was archived by the owner on Oct 19, 2023. It is now read-only.

Commit 61ec8a9

Browse files
committed
update example to include changing buttons
1 parent 5cdb606 commit 61ec8a9

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

RFKeyboardToolbarDemo/RFKeyboardToolbar/ViewController.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@
88

99
#import <UIKit/UIKit.h>
1010

11-
@interface ViewController : UIViewController
11+
@interface ViewController : UIViewController <UITextViewDelegate>
1212

1313
@end

RFKeyboardToolbarDemo/RFKeyboardToolbar/ViewController.m

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)