How to push key value into UITextView from custom

2019-06-02 08:49发布

问题:

I am building a virtual keyboard for a UITextView. All works well, I can display the keyboard and remove the keyboard as well as display the keystrokes. I am using the "stringByReplacingCharactersInRange: withString" method to place the new keystroke into the text view. This works but since it is replacing the string each time, the entry point goes to the end of the string. This all makes sense, but is not very usable. I can fix this by doing checks in my code but there might be something better...

So my question is this; Is there a way to push the new key to the UITextView directly without modifying the UITextView's text property's string manually? The manual states that I will have to manage the target/action myself, but I was wondering if I've missed an action to call. It seems that the Apple Default keyboard must have a slick way of punching the keystroke into the object without the obvious number of checks that I will have to do to make the typing smooth.

Any help will be greatly appreciated. Thanks, Rob

回答1:

Well, I didn't get any responses. So I figured out a way to do it so it is reasonable and simple. It's a matter of tracking the selected range. So when I wish to Backspace I use this technique.

NSRange currentRange = self.myTextView.selectedRange;
if (currentRange.length == 0) {
    currentRange.location--;
    currentRange.length++;
}
self.myTextView.text = [self.myTextView.text stringByReplacingCharactersInRange:currentRange withString:[NSString string]];
currentRange.length = 0;
self.myTextView.selectedRange = currentRange;

If I need to type a character this works.

NSRange currentRange = self.myTextView.selectedRange;
self.myTextView.text = [self.myTextView.text stringByReplacingCharactersInRange:currentRange withString:someCharacter];
currentRange.location++;
currentRange.length = 0;
self.myTextView.selectedRange = currentRange;

If anyone has a better way, I'd like to hear it.

Thanks,
Rob