2016-10-31 38 views
0

我想在Objective-C中創建一個定時器進度條like that。假設我有60秒的計時器。當計時器值增加時,這個進度條值將被更新,當我點擊十字按鈕時,它將重新初始化計時器。我怎樣才能做到這一點?iOS定時器進度條

+0

簽出'UIProgressView',雖然它可能不是你想要的。否則,你有沒有看過動畫UIView的寬度? –

+0

使用SubView創建自定義視圖。 subView應該是UIView。用定時器增加SubView的寬度。 – AshokPolu

回答

1
  1. 設置視圖層次方式如下:

enter image description here

Basicly你有containerViewprogressView。您將操作progress viewwidth constraint

所以,容器視圖有一個修復高度,並約束一切到超視圖。進度視圖有0個前導,頂部和底部約束,並且現在可以將寬度設置爲0。

你的視圖控制器應當看起來像這樣: enter image description here

ProgressView幀和約束:

enter image description here

ContainerView幀和constaints:

enter image description here

現在是時候在您的viewController中進行編碼了。

#import "ViewController.h" 

@interface ViewController() 
// Create IBOutlet for the progressView's width constraint 
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *progressViewWidthContraint; 

// Declare a timer 
@property (nonatomic, strong) NSTimer *progressTimer; 
@property (nonatomic, assign) CGFloat progressPerSecond; 

@end 

@implementation ViewController 

// Progress time can be changed on demand 
NSInteger kProgressTime = 60; 

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
// Lets setup how much should the progress be increased by a second 
    self.progressPerSecond = self.view.frame.size.width/kProgressTime; 
// Lets start showing the progress 
    [self startOrResetTimer]; 
} 

- (void)startOrResetTimer { 
// Just in case invalidate the timer before we would set it up 
    [self.progressTimer invalidate]; 
// Set the progressView's constant to its initial phase  
    self.progressViewWidthContraint.constant = 0; 
    [self.view setNeedsLayout]; 
    [self.view layoutIfNeeded]; 
// Create the timer  
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgress) userInfo:nil repeats:true]; 
} 

- (void)updateProgress { 
    // If the progress has reached the end of the screen, do not increase the constraint's constant 
    if (self.progressViewWidthContraint.constant == self.view.frame.size.width) { 
     return; 
    } 

    // Increase the constant by the previously calculated progress per second 
    self.progressViewWidthContraint.constant += self.progressPerSecond; 
    [self.view setNeedsLayout]; 
    [self.view layoutIfNeeded]; 
} 

// Hook this method to your reset button on the interface builder, and any time you press the button, it will reset the timer and the progressbar 
- (IBAction)didTapResetTimerButton:(UIButton *)sender { 
    [self startOrResetTimer]; 
} 

@end 

希望這有助於!