目标c中小时格式的倒数计时器

时间:2017-12-12 06:12:00

标签: ios objective-c timer

我在视图控制器中设置了一个计时器,当我给它任何静态编号时它工作正常。现在我想设置一个小时的计时器,一秒钟减少,当达到零时无效。我写了一些代码,

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

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

2 个答案:

答案 0 :(得分:0)

试试这个:

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是一个navBar图标及其操作

playPressed也是一个navBar图标及其动作

答案 1 :(得分:0)

请检查一下。

-(void) startCounter{
    if (countInt >= 0) {
        int minutes, seconds;
        int hours;

        countInt--;

        hours = countInt / 3600;
        minutes = (countInt % 3600) / 60;
        seconds = (countInt %3600) % 60;
        NSString *time = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];

        self.lblTimer.text = time;
    }
    if (countInt <= 0) {
        NSLog(@"TIME OUT");
        if ([timer isValid]) {
            [timer invalidate];
            timer = nil;
        }
    }
}
相关问题