通过改变uiview的layer的frame来实现进度条

时间:2022-09-07 21:32:14
#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(, , , 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<=) {
progressLayer.frame=CGRectMake(, , , self.frame.size.height);
}
else if (progress<=)
{
progressLayer.frame=CGRectMake(, , progress*currentViewWidth, self.frame.size.height);
}
else
{
progressLayer.frame=CGRectMake(, , 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(, , , )];
[self.view addSubview:self.progressView];
_timer=[NSTimer scheduledTimerWithTimeInterval: target:self selector:@selector(layerAnimation) userInfo:nil repeats:YES]; }
-(void)layerAnimation
{
self.progressView.progress=arc4random()%/100.0f;
self.progressView.layColor=[UIColor greenColor];
} @end