以下代码在 iOS < 7.0 中可以正常工作。在 iOS 7 中,当 UITextView 更新时,滚动会断断续续且不稳定。我不确定这是否是 iOS 7 中的错误,或者我做错了什么。
测试控制器.h
//TODO: Add UITextView in storyboard and tie to textView outlet
#define MAX_TEXT_VIEW_CHARACTERS 1000
@interface TestController : UIViewController {
NSMutableString *_outputText;
NSTimer *_outputTimer;
}
@property (strong, nonatomic) IBOutlet UITextView *textView;
@end
测试控制器.m
@implementation TestController
@synthesize textView;
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
_outputText = [NSMutableString stringWithCapacity:MAX_TEXT_VIEW_CHARACTERS];
_outputTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(outputLine:) userInfo:nil repeats:YES];
}
-(void)outputLine:(NSTimer *) theTimer {
static int i = 0;
//Run this 100 times
if (i > 99) {
[_outputTimer invalidate];
return;
}
[self outputToScreen:[NSString stringWithFormat:@"Some string %d\r", ++i]];
}
-(void)outputToScreen:(NSString *)str {
if (!str || !str.length) return; //Nothing to output
NSInteger outputTextSize = _outputText.length;
[_outputText appendString:str];
if (outputTextSize > MAX_TEXT_VIEW_CHARACTERS)
[_outputText deleteCharactersInRange:NSMakeRange(0, outputTextSize - MAX_TEXT_VIEW_CHARACTERS)];
self.textView.text = _outputText;
[self scrollOutputToBottom];
}
-(void)scrollOutputToBottom {
CGPoint p = [textView contentOffset];
[textView setContentOffset:p animated:NO];
[textView scrollRangeToVisible:NSMakeRange([textView.text length], 0)];
}
@end