iOS进度条演示
功能展示
- 点击“加载”按钮,启动进度条,显示“刷新”图标
- 点击“停止”按钮,停止进度条的加载,隐藏“刷新”图标
step1-添加属性
因为要定时更新进度条,所以需要添加一个定时器对象 timer
同时,也需要保存下当前的进度, count
@interface UIDemoViewController ()
@property (nonatomic, strong) NSTimer * timer;
@property NSUInteger count;
@end
step2-创建控件
self.count = 0;
- 创建进度条
// 创建进度条
UIProgressView * prog = [[UIProgressView alloc] initWithFrame:frame];
prog.tag = 100;
// prog.progressViewStyle = UIProgressViewStyleBar;
[self.view addSubview:prog];
- 创建更新图标
UIActivityIndicatorView * aiv = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
aiv.tag = 101;
aiv.color = [UIColor blueColor];
aiv.frame = CGRectMake(220, 65, 30, 30);
[self.view addSubview:aiv];
- 创建定时器
[self.timer setFireDate:[NSDate distantFuture]];
[self.timer fire];
- 创建启动、停止按钮
UIButton * start = [UIButton buttonWithType:UIButtonTypeSystem];
start.frame = CGRectMake(50, 100, 50, 44);
[start setTitle:@"加载" forState:UIControlStateNormal];
[start addTarget:self action:@selector(startLoad) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:start];
// 创建停止按钮
UIButton * stop = [UIButton buttonWithType:UIButtonTypeSystem];
stop.frame = CGRectOffset(start.frame, 80, 0);
[stop setTitle:@"停止" forState:UIControlStateNormal];
[stop addTarget:self action:@selector(stopLoad) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:stop];
step3-事件响应
[self.timer setFireDate:[NSDate distantPast]];
// 重新复位进度
self.count = 0;
// 显示加载动画
UIActivityIndicatorView * aiv = (UIActivityIndicatorView *)[self.view viewWithTag:101];
[aiv startAnimating];
}
- (void) stopLoad {
[self.timer setFireDate:[NSDate distantFuture]];
UIActivityIndicatorView * aiv = (UIActivityIndicatorView *)[self.view viewWithTag:101];
[aiv stopAnimating];
}
- (void) refresh {
UIProgressView * prog = (UIProgressView *)[self.view viewWithTag:100];
prog.progress = (self.count++) / 100.0;
NSLog(@"progress: %lf", prog.progress);
if (self.count >= 100) {
[self stopLoad];
}
}
注意
- 定时器的“停止”是 [self.timer setFireDate:[NSDate distantFuture]]; 代表设置,定时器的触发时间在未来,所以,肯定不会被触发。
- 将代表进度值的设置成 属性,当需要复位进度条时,只需要将 count 清零即可。