LoginSignup
8
6

More than 5 years have passed since last update.

iOS7のUITextViewで文末にカーソルを移動する際のバグの回避方法

Last updated at Posted at 2014-08-02

iOS7のUITextViewでカーソルを文末に移動するのに、以下のようにするとカーソルは文末に移動しますが、その後の動作がおかしくなる場合があります。

Objective-C
NSRange r = NSMakeRange(textView.text.length, 0);
textView.selectedRange = r;
[textView scrollRangeToVisible:r];

iOS7のUITextViewには文字の長さに関連したバグがあるようです。
これは以下のようにすることで回避できます。

Objective-C
UITextPosition *pos = textView.endOfDocument;
textView.selectedTextRange = [textView textRangeFromPosition:pos toPosition:pos];
CGRect caretRect = [textView caretRectForPosition:pos];
caretRect.size.height += textView.font.lineHeight;
[textView scrollRectToVisible:caretRect animated:NO];

ちなみにlineHeightを加算しているのは、最下行がキーボードの下に隠れるバグを回避するためです。また、animated:YESにすると、長文の場合に文末までスクロールしないことがあります。

8
6
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
8
6