UITextViewを末尾へスクロールさせる

UITextFieldのtext内容をUITextViewにどんどん追加していくということをやりたい時。
行数が増えても自動的にスクロールして一番下の行が表示されるようにしたい。

@interface MyViewController ()

@property (weak, nonatomic) IBOutlet UITextField *myTextField;
@property (weak, nonatomic) IBOutlet UITextView *myTextView;

@end

UITextViewのtextプロパティを変更する前に、scrollEnabledをNOにしておくところがポイントらしい。

あと、テキストの選択位置(カーソル位置?)にスクロールする機能もあるらしくて、その辺りの設定もしてあげると幸せになるっぽい。

よくわからないけど←

以下は@implementationの中身


- (void)viewDidAppear:(BOOL)animated
{
    
    //予めテキストビューの選択位置を設定
    NSString *viewText = _myTextView.text;
    NSRange range;
    range.location = [viewText length];
    _myTextView.selectedRange = range;
    
}
- (void)makeMyText {
    
    _myTextView.scrollEnabled = NO;
    
    NSString *newText = _myTextField.text;
    NSString *oldText = _myTextView.text;
    NSString *modifiedText = [NSString stringWithFormat:@"%@%@\n", oldText, newText];
    
    _myTextView.text = modifiedText;
    _myTextField.text = @"";
    
    [self scrollText];
 
}

- (void)scrollText {
    NSRange range;
    range.location = [_myTextView.text length];
    _myTextView.selectedRange = range;
    _myTextView.scrollEnabled = YES;
    
    CGFloat scrollY = _myTextView.contentSize.height + _myTextView.font.pointSize - _myTextView.bounds.size.height;
    CGPoint scrollPoint;
    
    if (scrollY < 0) {
        scrollY = 0;
    }
    scrollPoint = CGPointMake(0.0, scrollY);
    
    [_myTextView setContentOffset:scrollPoint animated:YES];
    
}

あとはテキスト送信時にmakeMyTextメソッドを呼べばOK。

人気の記事

タグ: , , ,

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*

Top