iOS项目开发实战——使用CALayer和定时器实现进度条

来源:互联网 发布:java jdk 32官网下载 编辑:程序博客网 时间:2024/06/15 11:04

     UIView作为CALayer的容器管理器,因其是更高层级的抽象,能实现的动画效果收到了很多限制。CALayer作为动画效果直接作用的实体,我们能利用很多的属性。这里我们将自定义一个进度条。

(1)ProgressView.h中的实现如下:

#import <UIKit/UIKit.h>@interface ProgressView : UIView@property (nonatomic,assign) CGFloat progress;//进度参数;@end

(2)ProgressView.m的实现如下:

#import "ProgressView.h"@interface ProgressView ()@property (nonatomic,strong) CALayer *progressLayer;@property (nonatomic,assign) CGFloat currentViewWdith;@end@implementation ProgressView- (instancetype)initWithFrame:(CGRect)frame{  self = [super initWithFrame:frame];  if (self) {        self.progressLayer = [CALayer layer];    self.progressLayer.frame = CGRectMake(0, 0, 0, frame.size.height);        self.progressLayer.backgroundColor = [UIColor redColor].CGColor;        [self.layer addSublayer:self.progressLayer];        //存储当前View的宽度值;    self.currentViewWdith = frame.size.width;      }  return self;}#pragma mark - 重写Set,Get方法;- (void)setProgress:(CGFloat)progress{    NSLog(@"执行22222222");  _progress = progress;    if (progress <= 0) {    _progressLayer.frame = CGRectMake(0, 0, 0, self.frame.size.height);  }  else if (progress <= 1){      //progress其实就是0——1的比例;    _progressLayer.frame = CGRectMake(0, 0, progress * _currentViewWdith, self.frame.size.height);      }  else {      _progressLayer.frame = CGRectMake(0, 0, _currentViewWdith, self.frame.size.height);  }}- (CGFloat)getProgress{    NSLog(@"执行33333333");  return _progress;}@end

(3)ViewController.m中的实现如下:

#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.view.backgroundColor = [UIColor blackColor];    self.progressView = [[ProgressView alloc] initWithFrame:CGRectMake(50, 100, 250, 3)];    self.progressView.layer.borderWidth = 1.0f;    self.progressView.backgroundColor = [UIColor yellowColor];    [self.view addSubview:self.progressView];    [self performSelector:@selector(layerAnimation)            withObject:nil             afterDelay:2.0f];    //创建定时器,每秒执行一回;  self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(layerAnimation) userInfo:nil repeats:true];  }int num = 0;- (void) layerAnimation{    NSLog(@"%d",num++);    //随机获取 0%-100%给layer赋值;  self.progressView.progress = num / 100.f; }@end

(4)最后的实现效果如下,每秒钟会增加1%。

.


github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

1 0
原创粉丝点击