iOS專案開發實戰——使用CALayer和定時器實現進度條

乞力馬紮羅的雪CYF發表於2015-09-20

     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  。歡迎大家訪問!

相關文章