【发布时间】:2014-06-20 10:51:24
【问题描述】:
我正在以编程方式更新UITextView 的attributedText。更新后我想打电话给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
那么,UITextViews 更新完成后我该如何更新?
更新:
根据 indyfromoz 的建议,在对文本视图进行编程更新后,我可以从委托方法 textViewDidChangeSelection 获得回调。但是,当调用该委托方法时,文本视图仍未完成更新。
如果我把日志语句放在那里:
- (void)textViewDidChangeSelection:(UITextView *)textView
{
CGFloat newContentHeight = textView.contentSize.height;
NSLog(@"bottom of new content: %f", newContentHeight);
}
报告的内容高度与更新前相同...
我将此归结为 UITextView 的一个错误。我先解决它,以后再看代码。
【问题讨论】:
标签: ios cocoa-touch ios7 uitextview nsnotificationcenter