用CALayer实现下载进度条
效果:
源码:
//
// ViewController.m
// ProgressView
//
// Created by YouXianMing on 14/11/18.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "ViewController.h" @interface ViewController () @property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) CALayer *layer; @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; self.view.backgroundColor = [UIColor blackColor]; // CALayer
_layer = [CALayer layer];
_layer.frame = CGRectMake(, , , );
_layer.backgroundColor = [UIColor redColor].CGColor;
[self.view.layer addSublayer:_layer]; // 定时器
_timer = [NSTimer scheduledTimerWithTimeInterval:.f
target:self
selector:@selector(timerEvent)
userInfo:nil
repeats:YES];
} /**
* 定时器
*/
- (void)timerEvent {
// 显式动画
_layer.frame = CGRectMake(, , arc4random()%, );
} @end
封装后的源码:
//
// ProgressView.h
// ProgressView
//
// Created by YouXianMing on 14/11/18.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import <UIKit/UIKit.h> @interface ProgressView : UIView @property (nonatomic, strong) UIColor *progressColor;
@property (nonatomic, assign) CGFloat progress; @end
//
// ProgressView.m
// ProgressView
//
// Created by YouXianMing on 14/11/18.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
// #import "ProgressView.h" @interface ProgressView () {
CALayer *_backLayer;
CGFloat _frameWidth;
CGFloat _layerWidth;
} @end @implementation ProgressView - (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_backLayer = [CALayer layer]; _frameWidth = self.bounds.size.width;
_layerWidth = ; _backLayer.frame = CGRectMake(, , _layerWidth, frame.size.height);
[self.layer addSublayer:_backLayer];
}
return self;
} @synthesize progressColor = _progressColor;
- (void)setProgressColor:(UIColor *)progressColor {
_progressColor = progressColor;
_backLayer.backgroundColor = _progressColor.CGColor;
}
- (UIColor *)progressColor {
return _progressColor;
} @synthesize progress = _progress;
- (void)setProgress:(CGFloat)progress {
_progress = progress; CGRect rect = _backLayer.frame;
if (_progress <= ) {
rect.size.width = ;
} else if (_progress >= ) {
rect.size.width = _frameWidth;
} else {
rect.size.width = _progress * _frameWidth;
} _backLayer.frame = rect;
}
- (CGFloat)progress {
return _progress;
} @end