/**
* 用CALayer定制下载进度条控件
* 1.单独创建出CALayer
* 2.直接修改CALayer的frame值,执行隐式动画,实现进度条效果
* 3.用定时器(NSTimer)模拟网络下载时提供的百分比数据
* 4.将CALayer封装进UIView子类中定制进度条控件
*/
自定义一个UIView,创建CALayer
#import <UIKit/UIKit.h> @interface WJProgressView : UIView @property (nonatomic,assign)CGFloat progress;//进度参数取值范围0~100
@property (nonatomic,strong)UIColor *progressColor;//颜色 @end
#import "WJProgressView.h" @interface WJProgressView () @property (nonatomic,strong)CALayer *progressLayer;
@property (nonatomic,assign)CGFloat currentViewWidth; @end @implementation WJProgressView - (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.progressLayer = [CALayer layer];
self.backgroundColor = [UIColor grayColor];
self.progressLayer.backgroundColor = [UIColor redColor].CGColor;
self.progressLayer.frame = CGRectMake(, , , frame.size.height);
[self.layer addSublayer:self.progressLayer];
//储存当前view的宽度值
self.currentViewWidth = frame.size.width;
}
return self;
} #pragma mark - 重写setter,getter方法 @synthesize progress = _progress;
- (void)setProgress:(CGFloat)progress {
_progress = progress;
if (progress <= ) {
self.progressLayer.frame = CGRectMake(, , , self.frame.size.height);
}else if (progress <= ) {
self.progressLayer.frame = CGRectMake(, , progress *self.currentViewWidth, self.frame.size.height);
}else {
self.progressLayer.frame = CGRectMake(, , self.currentViewWidth, self.frame.size.height);
}
} - (CGFloat)progress {
return _progress;
} @synthesize progressColor = _progressColor;
- (void)setProgressColor:(UIColor *)progressColor {
_progressColor = progressColor;
self.progressLayer.backgroundColor = progressColor.CGColor;
} - (UIColor *)progressColor {
return _progressColor;
}
向上面那样封装的话,只需改变progress进度属性就能改变CALayer的frame(隐式动画)
self.progressView.progress = arc4random()%/.f;
效果图: