程序很简单,关键是涉及多线程问题以及线程休眠问题
下面看下代码:
#import "ViewController.h"
@interface ViewController ()
{
UILabel *_label;
NSString *_str;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
_label = [[UILabel alloc] initWithFrame:CGRectMake(50, 200, 375-100, 300)];
_label.numberOfLines = 0;
_label.font = [UIFont systemFontOfSize:16];
_label.backgroundColor = [UIColor purpleColor];
_label.textColor = [UIColor blackColor];
[self.view addSubview:_label];
//开启线程
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(animationLabel) object:nil];
[thread start];
//初始化字符串,为我们最后显示内容
_str = @"感谢对本文的收看,希望能帮到你";
}
//线程的代码体,执行休眠
-(void)animationLabel
{
for (int i=0; i<_str.length; i++) {
//每次给Label显示的文字是从最前边到i+1个
[self performSelectorOnMainThread:@selector(refreshUI:) withObject:[_str substringWithRange:NSMakeRange(0, i+1)] waitUntilDone:YES];
[NSThread sleepForTimeInterval:0.3];
}
}
//执行主线程修改UI
-(void)refreshUI:(NSString *)contentStr
{
_label.text = contentStr;
}
@end