LoginSignup
5
5

More than 5 years have passed since last update.

UITextViewでカーソルを右端に持ってくる方法

Posted at

UITextViewにはselectedRangeというプロパティがあり、NSRange型で選択範囲を指定できます。NSRangeのメンバー変数にはlengthとpositionがあって、そのlengthを0にするとpositionによってカーソルの位置を指定することができます。しかし、長文が見た目上で改行されている場合、その行の右端にカーソルを持ってこようとしてposition指定しても、次の行の先頭にカーソルが来てしまいます。これを回避してカーソルを右端に表示する方法を発見しましたので開示します。
以下ではtextViewにUITextViewのインスタンスが格納されているとします。

Objective-C
UITextRange *cur = textView.selectedTextRange;
CGRect endRect = [textView caretRectForPosition:cur.end];
UITextPosition *pos = [textView closestPositionToPoint:CGPointMake(100000, endRect.origin.y + endRect.size.height / 2)];
textView.selectedTextRange = [textView textRangeFromPosition:pos toPosition:pos];
5
5
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
5
5