#import <UIKit/UIKit.h> @interface ProgressView : UIView @property (nonatomic,assign,setter=setProgressValue:) float progressValue; -(void)setProgressValue:(float)progressValue; @end
#import "ProgressView.h" @interface ProgressView () @property (nonatomic,strong) CALayer* proLayer; @property (nonatomic,strong) CATextLayer* textLayer; @end @implementation ProgressView - (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.proLayer = [CALayer layer]; self.proLayer.backgroundColor = [[UIColor redColor] CGColor]; self.proLayer.frame = CGRectMake(0, 0, 0, frame.size.height); [self.layer addSublayer:self.proLayer]; self.textLayer = [CATextLayer layer]; self.textLayer.backgroundColor = [[UIColor clearColor] CGColor]; self.textLayer.fontSize = 14; self.textLayer.foregroundColor = [[UIColor blackColor] CGColor]; self.textLayer.alignmentMode = @"center"; self.textLayer.frame = CGRectMake(0, 0, frame.size.width, frame.size.height); [self.layer addSublayer:self.textLayer]; } return self; } -(void)setProgressValue:(float)progressValue { _progressValue = progressValue; if (_progressValue<=0) { self.proLayer.frame = CGRectMake(0, 0, 0, self.frame.size.height); } else if (_progressValue>=1){ self.proLayer.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height); } else{ self.proLayer.frame = CGRectMake(0, 0, self.frame.size.width * _progressValue, self.frame.size.height); } self.textLayer.string = [NSString stringWithFormat:@"%.0f%%",round(_progressValue * 100) ]; } @end
#import "ViewController.h" #import "ProgressView.h" @interface ViewController () @property (nonatomic,strong) CALayer* layer; @property (nonatomic,strong) ProgressView* proView; @property (nonatomic,strong) NSTimer* timer1; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; self.proView = [[ProgressView alloc] initWithFrame:CGRectMake(100, 200, 100, 20)]; self.proView.layer.borderWidth = 1; [self.view addSubview:self.proView]; self.timer1 = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(ProgressChange) userInfo:nil repeats:YES]; } -(void)ProgressChange { float value = arc4random() % 100 / 100.f; self.proView.progressValue = value; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end能有动画效果,来自极客学院