OGeek|极客世界-中国程序员成长平台

标题: ios - Objective c中小时格式的倒数计时器 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:26
标题: ios - Objective c中小时格式的倒数计时器

我在我的 View Controller 中设置了一个计时器,当我给它任何静态数字时它工作正常。现在我想设置一个一小时的计时器,它以一秒递减并在达到零时失效。我已经写了一些代码,

countInt=10;
self.lblTimer.text=[NSString stringWithFormat"%i",countInt];
timer=[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selectorselector(startCounter) userInfo:nil repeats:YES];
-(void)startCounter{
countInt -=1;
self.lblTimer.text=[NSString stringWithFormat"%i",countInt];

if (countInt==0) {
    [timer invalidate];
}
}



Best Answer-推荐答案


试试这个:

import UIKit

class ViewController: UIViewController{

    @IBOutlet weak var timerLbl: UILabel!

    var timer = Timer()

    @IBAction func pausePressed(_ sender: Any) {
        timer.invalidate()
    }

    @IBAction func playPressed(_ sender: Any) {
        if timer.isValid {
            timer.invalidate()
        }
        timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(reduceSeconds), userInfo: nil, repeats: true)
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        timerLbl.text = "180"
        timerLbl.font = UIFont.boldSystemFont(ofSize: 32)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
       }

    func reduceSeconds() -> Void {
        timerLbl.text = String(Int(timerLbl.text!)! - 1)
    }
}

这将按 180 秒运行,计数器将减少 1(根据需要),您可以将其重置或设置为您喜欢的方式。

注意:

pausePressed 是一个导航栏图标和对它的操作

playPressed 也是一个导航栏图标和对它的操作

关于ios - Objective c中小时格式的倒数计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47766344/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4