等待UITextView完成更新文本(iOS 7.1)

我是以编程方式更新UITextViewattributedText 。 在更新之后,我想调用setContentOffset以便我可以滚动以定位新文本。

我遇到的问题是文本视图更新其文本有延迟。

使用以下代码,调试日志输出相同的值:

 - (void)appendToTextView:(NSString*)text { CGFloat bottomOfCurrentContent = _pastedText.contentSize.height; NSLog(@"Bottom of content, before = %f", bottomOfCurrentContent); NSString* textViewText = text; BOOL previouslyHadText = _pastedText.text.length > 0; if (previouslyHadText) { textViewText = [NSString stringWithFormat:@"%@\n%@", _pastedText.text, textViewText]; } NSMutableParagraphStyle* paragraphStyle = [[NSMutableParagraphStyle alloc] init]; paragraphStyle.lineSpacing = _lineSpacing; NSDictionary *attribute = @{ NSParagraphStyleAttributeName : paragraphStyle, NSFontAttributeName : [UIFont systemFontOfSize:18.0] }; _pastedText.attributedText = [[ NSAttributedString alloc] initWithString:textViewText attributes:attribute]; if (previouslyHadText) { CGFloat bottomOfNewContent = _pastedText.contentSize.height; NSLog(@"Bottom of content, after = %f", bottomOfNewContent); // Set content offset... } } 

例如,输出:

 2014-05-03 21:52:57.181 thisApp[7011:60b] Bottom of content, before = 244.000000 2014-05-03 21:52:57.182 thisApp[7011:60b] Bottom of content, after = 244.000000 

如果我人为地等待文本视图完成更新,内容将按预期报告…

 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ CGFloat bottomOfNewContent = _pastedText.contentSize.height; NSLog(@"Bottom of content, after = %f", bottomOfNewContent); // Set content offset... }); 

输出:

 2014-05-03 23:12:39.694 thisApp[7050:60b] Bottom of content, before = 244.000000 2014-05-03 23:12:44.698 thisApp[7050:60b] Bottom of content, after = 451.000000 

那么,当UITextView的更新完成后,如何更新?

更新:

根据indyfromoz的建议,我可以在对文本视图进行编程更新之后,从委托方法textViewDidChangeSelection中获取回调。 但是,当调用该委托方法时,文本视图仍未完成更新。

如果我在那里删除日志语句:

 - (void)textViewDidChangeSelection:(UITextView *)textView { CGFloat newContentHeight = textView.contentSize.height; NSLog(@"bottom of new content: %f", newContentHeight); } 

报告的内容高度与更新前的内容高度相同…

我把它归结为UITextView一个错误。 我现在要解决它,并在将来再次查看代码。

UITextView插入新文本后,您可以使用scrollRangeToVisible (通常通过scrollRangeToVisible委托方法)来滚动文本视图的内容。 iOS 7中的UITextView有一些错误, Peter有一篇很好的文章讨论过这个问题 , Brent Simmons有一个近乎完美的解决方案来滚动UITextView中的内容。