@implementation FETextView - (id)initWithFrame:(CGRect)frame text:(NSString *)text { self = [super initWithFrame:frame]; if (self) { [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(appendNextCharacter) userInfo:nil repeats:YES]; _text = [text copy]; self.backgroundColor = [UIColor whiteColor]; } return self; } //原文地址www.2cto.com - (void)appendNextCharacter { for (NSUInteger i = 0; i <= self.index; i++) { if (i < self.text.length) { UILabel *label = [[UILabel alloc] init]; label.text = [self.text substringWithRange:NSMakeRange(i,1)]; label.opaque = NO; [label sizeToFit]; CGRect frame = label.frame; frame.origin = [self originAtIndex:i fontSize:label.font.pointSize]; label.frame=frame; [self addSubview:label]; } } self.index++; } - (CGPoint)originAtIndex:(NSUInteger)index fontSize:(CGFloat)fontSize { if (index == 0) { return CGPointZero; } else { CGPoint origin = [self originAtIndex:index-1 fontSize:fontSize]; NSString * prevCharacter = [self.text substringWithRange:NSMakeRange(index-1,1)]; CGSize prevCharacterSize = [prevCharacter sizeWithAttributes:@{ NSFontAttributeName: [UIFont systemFontOfSize:fontSize] }]; origin.x += prevCharacterSize.width; if (origin.x > CGRectGetWidth(self.bounds)) { origin.x = 0; origin.y += prevCharacterSize.height; } return origin; } } @end
主視圖控制器的調用代碼:
NSString * path = [[NSBundle mainBundle] pathForResource:@"FlyElephant" ofType:@"txt"]; FETextView *textView = [[FETextView alloc] initWithFrame:CGRectMake(0, 64, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds)) text:[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]]; [self.view addSubview:textView];