如何自定义一个UIProgressView

来源:互联网 发布:微信 for mac 2.0 dmg 编辑:程序博客网 时间:2024/05/18 03:32

ViewController.m里的文件

#import "ViewController.h"#import "MyProgressView.h"@interface ViewController ()            @end@implementation ViewController            - (void)viewDidLoad {    [super viewDidLoad];        //特征:    //1. 取值范围: 0-1.0    //2.    UIProgressView *progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(10, 100, 280, 140)];    progressView.progress = .5;    progressView.tag = 100;    [self.view addSubview:progressView];        MyProgressView *myProgressView = [[MyProgressView alloc] initWithFrame:CGRectMake(10, 160, 280, 20)];    myProgressView.progress = .5;    myProgressView.tag = 101;    [self.view addSubview:myProgressView];        //创建一个新的视图,并且将它设置给进度条的tView属性    //视图显示:addSubview-//    myProgressView.tView = [[UIView alloc] init];//    myProgressView.progress = 1.9;    myProgressView.progressColor = [UIColor redColor];    myProgressView.progressColor = [UIColor purpleColor];    myProgressView.backgroundColor = [UIColor greenColor];        myProgressView.frame = CGRectMake(10, 160, 280, 40);}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}- (IBAction)didSlide:(UISlider *)sender {    UIProgressView *progressView = (UIProgressView *)[self.view viewWithTag:100];    progressView.progress = sender.value;        MyProgressView *myProgressView = (MyProgressView *)[self.view viewWithTag:101];    myProgressView.progress = sender.value;}@end

自定义的progress的类

#import <UIKit/UIKit.h>@interface MyProgressView : UIView@property (nonatomic) float progress;@property (nonatomic, strong) UIColor *progressColor;@end

#import "MyProgressView.h"@interface MyProgressView ()@property (nonatomic, strong) UIView *tView;@end@implementation MyProgressView- (instancetype)initWithFrame:(CGRect)frame{    self = [super initWithFrame:frame];    if (self) {        self.backgroundColor = [UIColor grayColor];                _tView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, frame.size.height)];        _tView.backgroundColor = [UIColor blueColor];        [self addSubview:_tView];    }    return self;}- (void)setProgress:(float)progress{    if (progress >= 1.0) {        _progress = 1.0;    }    else if (progress <= 0) {        _progress = 0.0;    }    else {        _progress = progress;    }        _tView.frame = CGRectMake(0, 0, _progress * self.frame.size.width, self.frame.size.height);}- (void)setProgressColor:(UIColor *)progressColor{    _progressColor = progressColor;        _tView.backgroundColor = progressColor;}//*******重点*******//1. 一定不能手动调用!!!!!!//3. 自动调用的情况://  a. 改变父视图frame...之类的与布局相关的方法时//  b. 改变它本身的frame/bounds...的时候//  c. 添加到父视图上时(addSubview:)//  d. 调用它的setNeedsLayout方法的时候(可能)- (void)layoutSubviews{    //2. 一般情况下    [super layoutSubviews];        _tView.frame = CGRectMake(0, 0, _progress * self.frame.size.width, self.frame.size.height);}@end


0 0