iOS 视图类似于 Android 上的 Chronometer



在Android上,这里有一个名为Chronometer details的标准视图。iOS 是否有类似的视图或执行类似操作的库?

无论如何我都没有找到这样做,所以我在这里创建了一个带有 GPL 许可证的要点,如果有人兴奋地将其设为库:)

我会为此使用Timer

var timer = Timer()
timer = Timer(timeInterval: 0.01, target: self, selector: #selector(update), userInfo: nil, repeats: false)
@IBAction func start(sender: UIButton) {
     timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.update(_:)), userInfo: nil, repeats: true)
     RunLoop.current.add(timer, forMode: RunLoop.Mode.common)
    startTime = Date() // new instance variable that you would need to add.
}
func update() {
    let elapsedTime = Date().timeIntervalSince(startTime)
    let currTime = totalTime - elapsedTime
    //total time is an instance variable that is the total amount of time in seconds that you want
    countDown.text = String(currTime)
    if currTime < 0 {
        timer.invalidate()
        //do other stuff that you need to do when time runs out.
    }
}

如果您想要更小或更大的时间片段,只需将其更改为 Interval 参数即可。此外,您仍然必须解决创建一些逻辑来拆分分钟/秒等。使用Date方法并递增某些实例变量。

为什么不在计时器模式下使用 UIDatePicker?

UIDatePicker* datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 206)];
datePicker.datePickerMode = UIDatePickerModeCountDownTimer;
datePicker.countDownDuration = 60*5;
[self.view addSubview:datePicker];

最新更新