1.思路分析
进度肯定是不停改变的,所以我们肯定需要定时器NSTimer操作,监听Label控件进度文字的改变,从而来设计下载视图的圆形
设计下载进度视图,需要我们提供进度值 -> 来确定绘制圆的大小
2.实现
- 自定义DrawView视图,用来绘制下载进度
// .h文件
#import <UIKit/UIKit.h>
@interface DrawView : UIView
@property (nonatomic, assign) CGFloat value;
@end
// . m文件
#import "DrawView.h"
@implementation DrawView
- (void)drawRect:(CGRect)rect {
// Drawing code
UIBezierPath *path = [[UIBezierPath alloc] init];
CGPoint center = CGPointMake(self.frame.size.width * 0.5, self.frame.size.height * 0.5);
CGFloat radius = self.frame.size.width * 0.5 - 5;
CGFloat startAngle = 0;
CGFloat endAngle = self.value / 100 * M_PI * 2;
[path addArcWithCenter:center radius:radius startAngle:startAngle endAngle:endAngle clockwise:YES];
[path stroke];
}
@end
- 使用DrawView,实现下载进度动态显示
#import "ViewController.h"
#import "DrawView.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UILabel *lableView;
@property (weak, nonatomic) IBOutlet DrawView *grayView;
@property (nonatomic, weak) NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.lableView.text = @"0.0%";
[self.lableView sizeToFit];
}
// 改变lable的文字,然后重绘灰色视图上的进度条进度
- (void)change{
NSString *value = [self.lableView.text stringByReplacingOccurrencesOfString:@"%" withString:@""];
if ([value doubleValue] >= 100) {
[NSTimer initialize];
return;
}
CGFloat lastValue = [value doubleValue] + 1;
self.lableView.text = [NSString stringWithFormat:@"%.0f%%", lastValue];
[self.lableView sizeToFit];
// 重绘
self.grayView.value = lastValue;
// setNeedsDisplay方法会调用drawRect:方法,重绘灰色视图上的进度条进度
[self.grayView setNeedsDisplay];
}
- (void)touchesBegan:(nonnull NSSet<UITouch *> *)touches withEvent:(nullable UIEvent *)event{
// 创建定时器
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(change) userInfo:nil repeats:YES];
}
- (void)dealloc{
// 停止定时器
[NSTimer initialize];
}
@end