当我尝试在没有计时器的情况下做一个小计时器时我的代码运行良好但是我的标签没有显示时间,因为它运行错误了什么?
ViewController.swift:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var out4: UILabel!
@IBOutlet weak var out1: UIButton!
@IBOutlet weak var out2: UITextField!
@IBOutlet weak var out3: UILabel!
@IBAction func click(_ sender: Any) {
if out2.text != ""{
var counterheure:Int = 23;
var counterminute:Int = 60;
var countersec:Int = 60;
var counter:Int;
counter = Int(out2.text!)!;
counter = counter - 1;
while counter != 0 {
out3.text = "Days : \(counter); Hours : \(counterheure); Minutes : \(counterminute); Seconds : \(countersec); left before your next exam";
countersec = countersec - 1;
sleep(1);
if countersec == 0{
counterminute = counterminute - 1;
countersec = 60;
if counterminute == 0{
counterheure = counterheure - 1;
counterminute = 60;
if counterheure == 0{
counter = counter - 1;
counterheure = 24;
}
}
}
}
}
}
}
答案 0 :(得分:1)
因为你的循环阻塞了主线程,它也负责更新UI。
我建议使用计时器:
let timer = Timer(timeInterval: 1, repeats: true) { (timer) in
// This is called every second
}