15
15

More than 5 years have passed since last update.

[Objective-C] キャレットの位置を調整

Posted at

UITextViewなどでキャレット(カーソル)の位置を調整したい場合があります。
その際に利用するのはUITextRangeUITextPositionです。

UITextRangeはテキストのレンジ(範囲)を表現するクラスです。
プレーンテキストだけであればそれほど問題は複雑ではありませんが、HTMLテキストなどを考えると、見た目の選択状態と内部的な選択状態に差が生じます。
(例えば、「テキスト」という4文字を選択していても、HTMLではタグが複雑になっていて、内部的には数文字から数十文字を選択している状態かもしれません)

キャレットの位置を任意の場所に

キャレットを任意の位置に移動するには、UITextView.selectedTextRangeUITextRangeを設定することで実現できます。

UITextRange    *range    = aTextView.selectedTextRange;
UITextPosition *position = [aTextView positionFromPosition:range.start
                                                    offset:-1]; // キャレットを現在の位置からひとつ後ろに移動する(-1)

aTextView.selectedTextRange = [aTextView textRangeFromPosition:position
                                                      toPosition:position];

キャレットの位置を先頭に

aTextView.selectedTextRange = [aTextView textRangeFromPosition:textView.beginningOfDocument
                                                      toPosition:aTextView.beginningOfDocument];
15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15