UITextView automatic scroll down

前端 未结 9 1702
遇见更好的自我
遇见更好的自我 2020-12-14 15:33

I have an UIView and I add a editable UITextView to it,

UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 2         


        
9条回答
  •  情歌与酒
    2020-12-14 16:27

    I found that if the text added to the UITextView contained carriage returns, then the textview would not scroll correctly.

    I added the logic as follows to allow the bounds to be correctly calculated before scrolling to range.

    BOOL autoscroll = NO;
    
    //I added a 10 px buffer here to allow for better detection as the textview is auto populated 
    if (textView.contentOffset.y >= (textView.contentSize.height - textView.frame.size.height - 10))
    {
        autoscroll = YES;
    }
    
    [textView setText:messageString];
    [textView layoutSubviews];
    
    if(autoscroll) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)),     dispatch_get_main_queue(), ^{
            [textView scrollRangeToVisible:NSMakeRange(textView.text.length - 1, 1)];
        });
    }
    

提交回复
热议问题