开发者

How to push key value into UITextView from custom keyboard in iOS

开发者 https://www.devze.com 2023-02-06 06:53 出处:网络
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 \"stringByReplacingCharactersInRan

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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号