Handle marked text on iOS keyboard

1.9k views Asked by At

According to the doc,

Marked text, which is part of multistage text input, represents provisionally inserted text that the user has yet to confirm. It is styled in a distinctive way. The range of marked text always contains within it a range of selected text, which might be a range of characters or the caret.

And in the chapter Managing the Keyboard, Figure 5-2 shows what the marked text is:

enter image description here

Given the 4th & 6th image, the top bar on the keyboard presents the marked text, like "修", "修改", "修身", etc.

What I'm confused about is HOWTO :

  • Detect the user tap on the marked text. It's to replace the text selected, or just inserted the marked text.
  • Show custom text on the bar. For example, [textView showMarkedText:@"hello" atIndex:0].

Thanks.

1

There are 1 answers

0
liuyaodong On

Actually, you are kind of confused with the "marked text" and the "candidate text".

Take the Chinese-Handwriting keyboard for instance, the symbol "修" lies on the note is called "marked text", which has a distinctive style. And the "修", "修改", "修身", ... on the keyboard, you can call them "candidates"(The bar where they placed is named "candidate bar", if you inspect the view hierarchy of the keyboard).

There are some interfaces to operate on marked text. You could take a look at UITextInput protocol which UITextView and UITextField are confirmed to. -setMarkedText:selectedRange: and -unmarkText will do the tricky.

There is no public API to operate on the candidate bar and how to detect the tap on it is undocumented as well. But you can indirectly detect that by implementing -textView:shouldChangeTextInRange:replacementText: and -textViewDidChange: in UITextViewDelegate protocol if you are using UITextView (or the counterpart methods for UITextField if you are using it).

P.S: There is, at least, as I know, an exception for the Chinese keyboard, which is kind of like a bug. When you tap the candidate bar of a Chinese keyboard, the text you tapped is applied to your UITextView(or UITextField) without -textView:shouldChangeTextInRange:replacementText: triggered. But -textViewDidChange: will be invoked eventually.

Hope it could help.