I've been trying to implement this toolbar, where only the 'Next' button is enabled when the top textField is the firstResponder and only the 'Previous' button is enabled when the bottom textField is the firstResponder.
It kind of works, but what keeps happening is I need to tap the 'Previous'/'Next' buttons twice each time to enable/disable the opposing button.
Am I missing something in the responder chain that's making this happen?
Here's my code:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.topText becomeFirstResponder];
}
- (UIToolbar *)keyboardToolBar {
UIToolbar *toolbar = [[UIToolbar alloc] init];
[toolbar setBarStyle:UIBarStyleBlackTranslucent];
[toolbar sizeToFit];
UISegmentedControl *segControl = [[UISegmentedControl alloc] initWithItems:@[@"Previous", @"Next"]];
[segControl setSegmentedControlStyle:UISegmentedControlStyleBar];
segControl.momentary = YES;
segControl.highlighted = YES;
[segControl addTarget:self action:@selector(changeRow:) forControlEvents:(UIControlEventValueChanged)];
[segControl setEnabled:NO forSegmentAtIndex:0];
UIBarButtonItem *nextButton = [[UIBarButtonItem alloc] initWithCustomView:segControl];
NSArray *itemsArray = @[nextButton];
[toolbar setItems:itemsArray];
return toolbar;
}
- (void)changeRow:(id)sender {
int idx = [sender selectedSegmentIndex];
if (idx == 1) {
[sender setEnabled:NO forSegmentAtIndex:1];
[sender setEnabled:YES forSegmentAtIndex:0];
self.topText.text = @"Top one";
[self.bottomText becomeFirstResponder];
}
else {
[sender setEnabled:NO forSegmentAtIndex:0];
[sender setEnabled:YES forSegmentAtIndex:1];
self.bottomText.text =@"Bottom one";
[self.topText becomeFirstResponder];
}
}
-(void)textFieldDidBeginEditing:(UITextField *)textField {
if (!textField.inputAccessoryView) {
textField.inputAccessoryView = [self keyboardToolBar];
}
}
Try this :-
you dont need to enable other item as they reinitialise every time when keyboard changes ....
Okay, after looking at the brilliant BSKeyboardControls, I tried implementing the enabling and disabling of the segmented control in
textFieldDidBeginEditing
, instead of where my@selector
was. I also introduced a variable for the segmented control. It works now. Here's the amended code snippet:Here is a
UIViewController
extension that I use whenever I need a group ofUITextField
s to provide navigation via input accessory. No need to useUITextField
delegation with this approach, and adding the behavior to multiple forms becomes a single-liner. Also supports the 'Done' button to dismiss.example:
Here's a reasonable arrow icon.
My suggestion here is "don't reinvent the wheel".
Having
Prev
andNext
button over a keyboard for switching betweenUITextView
s is so common that you can find many good implementations ready to use.Check out BSKeyboardControl, for instance.
Swift:
In UITextFieldDelegate
Updated for Swift 3.0
And then:
Remember to change thange "ContactViewController" to the name of your View Controller.