gpt4 book ai didi

iOS 定时器进度条

转载 作者:行者123 更新时间:2023-11-28 21:19:20 25 4
gpt4 key购买 nike

我想创建一个定时器进度条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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com