Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get UITextFieldDelegate.shouldChangeCharactersInRange to fire with custom inputView?

I have a custom keyboard that I'm using to edit the text in mytextField and it works great. However, I can never get the shouldChangeCharactersInRange delegate to execute using my custom keyboard. It does execute when I use my actual keyboard(obviously not the default iPhone keyboard, since I'm set mytextField.inputView = numberPad.view). What should I do to cause the shouldChangeCharactersInRange delegate to fire using the custom keyboard? BTW, the custom keyboard is just a bunch of buttons.

- (void) numberPadPressed: (UIButton *)sender {
    [mytextField insertText:[[NSNumber numberWithInt:sender.tag] stringValue]];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *resultingString = [textField.text stringByReplacingCharactersInRange: range withString: string];
    NSLog(@"shouldChangeCharactersInRange: %@", resultingString);
    return true;
}

- (void)viewDidLoad {
    mytextField.text = @"";
    mytextField.inputView = numberPad.view;
    mytextField.delegate = self;
    [mytextField becomeFirstResponder];
}
like image 249
docchang Avatar asked Jan 12 '11 21:01

docchang


1 Answers

You will never get the shouldChangeCharactersInRange called with a custom keyboard.

What you can get is the event UIControlEventEditingChanged of the UITextField. So instead of relying on shouldChangeCharactersInRange method (which is known to be buggy in addition), you should rely on this event, that will be fired each time the user changes the content of the text field.

[textField addTarget:self action:@selector(myTextfieldChangedMethod:) forControlEvents:UIControlEventEditingChanged];

If you modify yourself the text field with your custom keyboard, just call this method to notify all listeners of the event UIControlEventEditingChanged.

[textField sendActionsForControlEvents:UIControlEventTouchUpInside];
like image 96
jptsetung Avatar answered Nov 13 '22 15:11

jptsetung