matmartinez / MMNumberKeyboard

A simple keyboard to use with numbers and, optionally, a decimal point.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Delegate method does not provide the range of the text that will be inserted

gunesmert opened this issue · comments

There is no range information provided on delegate method.
- (BOOL)numberKeyboard:(MMNumberKeyboard *)numberKeyboard shouldInsertText:(NSString *)text
Every number is being added to the end of the text.

Realised that, issue should be resolved on my side. Closing the issue.

I believe this is still a valid issue. While usually text is appended, you could also select a part of the entered text and then replace it with the next insert. Without range information, you cannot reliably calculate the length of the text (after the insert).

@shagedorn that's correct, the text isn't always appended (or added at all, for the same reason).

If you care about text length, the current selected text range can be obtained directly from your input view (see the <UIText​Input> protocol).

This seemed weird to me at first too. Range information seems to be missing from the -numberKeyboard: shouldInsertText: delegate method. But keyboards don't know about the content that's being edited, like for instance an UITextView does.

So, you need to do this manually like so:

- (BOOL)numberKeyboard:(MMNumberKeyboard *)numberKeyboard shouldInsertText:(NSString *)text
{
      UITextField *textField = self.myTextFieldThatIsBeingEdited;
      NSRange selectedRange = textField.selectedRange
     
      NSString *proposedString = [textField.text stringByReplacingCharactersInRange:selectedRange withString:text];
     
      return (...); // Return something that makes sense to you based on the new string.
}

Yes, that's what I did when I was using it.

Thanks for your explanation :)