iOS中 UIProgressView 技术分享

时间:2024-04-22 00:05:05

UIProgressView 继承自UIView,用来显示进度的,如音乐,视频的缓冲进度,文件的上传下载进度等.让用户知道当前操作完成了多少,离操作结束还有多远

AppDelegate.m

  ProgressViewController *progressVC = [[ProgressViewController alloc]init];
    self.window.rootViewController = progressVC;
    [progressVC release];

ProgressViewController.m

@interface ProgressViewController ()
@property (nonatomic,retain) UIProgressView *progressView;
@property (nonatomic,retain) UILabel *label;
@property (nonatomic,retain) NSTimer *timer;
@end

@implementation ProgressViewController
- (void)dealloc
{
    self.progressView = nil;
    self.label = nil;
    self.timer = nil;
    [super dealloc];
}

介绍相关 UIProgressView 的属性及用法:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor brownColor];

     //UIProgressView 继承自UIView,用来显示进度的,如音乐,视频的缓冲进度,文件的上传下载进度等.让用户知道当前操作完成了多少,离操作结束还有多远

    //1.创建一个progress对象,有自己的初始化方法,创建的同时指定progress的样式,是个枚举,系统提供了2种样式
    self.progressView = [[UIProgressView alloc]initWithProgressViewStyle:(UIProgressViewStyleDefault)];

    //设置progress的frame,不用设置高度,设置的高度对进度条的高度没影响
    _progressView.frame = CGRectMake(20, 150, 280, 0);

    //2.配置属性
    //2.1 设置当前进度值,范围在0.0~1.0,不可以修改最大值和最小值,默认值是0.0
//    _progressView.progress = 0.5;

    //2.2 设置轨道(未走过进度)的颜色
    _progressView.trackTintColor = [UIColor whiteColor];

    //2.3 设置进度条(已走过进度)的颜色
    _progressView.progressTintColor = [UIColor redColor];

    //3.添加到self.view
    [self.view addSubview:self.progressView];

    //4.释放
    [self.progressView release];

    //创建一个定时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(progressChanged) userInfo:nil repeats:YES];

    //调用label布局
    [self layoutLable];
}

布局label:

- (void)layoutLable{
    self.label = [[UILabel alloc]initWithFrame:(CGRectMake(120, 200, 80, 40))];
    _label.backgroundColor = [UIColor greenColor];
    _label.font = [UIFont systemFontOfSize:22];
    [self.view addSubview:self.label];
}

实现定时器的方法:

- (void)progressChanged{
    if (_progressView.progress >= 1.0) {
        [self.timer invalidate];
    }
    _progressView.progress += 0.01;

    //找一个float类型的变量接受当前progress的数值
    float progress = self.progressView.progress * 100;
    //使用接受的数值初始化一个字符串,用于label的显示
    NSString *string = [NSString stringWithFormat:@"%.1f%%",progress];
    _label.text = string;
    self.label.textAlignment = NSTextAlignmentCenter;
}

最终效果:

iOS中 UIProgressView 技术分享