#import <UIKit/UIKit.h>
@interface ProgressView : UIView
@property(nonatomic,assign)CGFloat progress;
@property(nonatomic,strong)UIColor *layColor;
@end
#import "ProgressView.h"
@interface ProgressView ()
{
CALayer *progressLayer;
CGFloat currentViewWidth;//当前view的宽度
}
@end
@implementation ProgressView
@synthesize progress=_progress;
@synthesize layColor=_layColor;
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
progressLayer=[CALayer layer];
progressLayer.frame=CGRectMake(0, 0, 0, frame.size.height);
progressLayer.backgroundColor=[UIColor redColor].CGColor;
[self.layer addSublayer:progressLayer];
currentViewWidth=frame.size.width;
}
return self;
}
-(void)setProgress:(CGFloat)progress
{
_progress=progress;
if (progress<=0) {
progressLayer.frame=CGRectMake(0, 0, 0, self.frame.size.height);
}
else if (progress<=1)
{
progressLayer.frame=CGRectMake(0, 0, progress*currentViewWidth, self.frame.size.height);
}
else
{
progressLayer.frame=CGRectMake(0, 0, currentViewWidth, self.frame.size.height);
}
}
-(CGFloat)progress
{
return _progress;
}
-(void)setLayColor:(UIColor *)layColor
{
_layColor=layColor;
self.layer.backgroundColor=layColor.CGColor;
}
-(UIColor *)layColor
{
return _layColor;
}
@end
#import "ViewController.h"
#import "ProgressView.h"
@interface ViewController ()
@property(nonatomic,strong)ProgressView *progressView;
@property(nonatomic,strong)NSTimer *timer;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.progressView=[[ProgressView alloc]initWithFrame:CGRectMake(20, 20, 290, 3)];
[self.view addSubview:self.progressView];
_timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(layerAnimation) userInfo:nil repeats:YES];
}
-(void)layerAnimation
{
self.progressView.progress=arc4random()%100/100.0f;
self.progressView.layColor=[UIColor greenColor];
}
@end