我在视图控制器中设置了一个计时器,当我给它任何静态编号时它工作正常。现在我想设置一个小时的计时器,一秒钟减少,当达到零时无效。我写了一些代码,
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];
}
}
答案 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;
}
}
}