iOS 定时器进度条

标签 ios objective-c

我想创建一个定时器进度条like that在 objective-C 中。假设我有一个 60 秒的计时器。当计时器值增加时,此进度条值将更新,当我点击十字按钮时,它将重新初始化计时器。我该怎么做?

最佳答案

  1. 按以下方式设置 View 层次结构:

enter image description here

基本上你有一个 containerView 和一个 progressView。您将操纵进度 View 宽度约束

因此,容器 View 具有固定高度,并将所有内容都约束到父 View 。进度 View 有 0 个前导、顶部和底部约束,现在让我们将宽度设置为 0。

你的 View Controller 应该是这样的: enter image description here

ProgressView 框架和约束:

enter image description here

ContainerView 框架和约束:

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

希望对您有所帮助!

关于iOS 定时器进度条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40338420/

相关文章:

objective-c - 为什么这个委托(delegate) - 协议(protocol)没有响应?

objective-c - 以编程方式自动锁定 iPhone

ios - 从 ViewController 实例化一个 DrawRect View

ios - 使用Application Loader上载IPA时无效的启动镜像错误上传,错误ITMS-90094

javascript - 在非文本元素上的 Web 应用程序中触发 iOS 键盘

ios - iPhone - 如何从一组 UILabel 中进行选择?

objective-c - HTML 到 NSMutableAttributedString 在 ios 6 中不起作用

ios - CoreGraphics 是否支持 Apple 设备上的 Metal?

ios - Swift-使用 UIScrollView 时如何定位项目

ios - Pod 安装不下载框架