@IBOutlet var timeLabel: UILabel!
var timer = Timer()
let now = Date()
let userCalendar = Calendar.current
let formatter = DateFormatter()
func printTime() {
formatter.dateFormat = "MM/dd/yy hh/mm/ss a"
let startTime = now
let endTime = formatter.date(from: "01/01/17 00/00/00 a")
let difference = userCalendar.dateComponents([.month, .day, .year, .hour, .minute, .second], from: startTime, to: endTime!)
timeLabel.text = "Yılbaşına \(difference.month!) ay, \(difference.day!) gün, \(difference.hour!) saat, \(difference.minute!) dakika, \(difference.second!) saniye kaldı"
print("hello world")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 1,
target: self,
selector: #selector(ViewController.printTime),
userInfo: nil,
repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
我正在使用Xcode 8和Swift 3.当我运行此代码时,它每秒都会写入控制台“hello world”,但是当计时器运行时它不是更新标签。我想每秒钟倒计时一次。
答案 0 :(得分:0)
试试这个:
DispatchQueue.main.after(when: .now() + 1.0) { //after one second
timeLabel.text = "Yılbaşına \(difference.month!) ay, \(difference.day!) gün, \(difference.hour!) saat, \(difference.minute!) dakika, \(difference.second!) saniye kaldı"
}
答案 1 :(得分:0)