我有一个标签,以12小时格式显示当前时间。
但是,每次分钟/小时更改时,它都不会更新/刷新时间。
我需要它在时间变化时自动将标签更改为当前时间。
答案 0 :(得分:11)
Swift 3解决方案
class ViewController {
@IBOutlet weak var timeLabel: UILabel!
var timer: Timer?
let formatter: DateFormatter = {
let tmpFormatter = DateFormatter()
tmpFormatter.dateFormat = "hh:mm a"
return tmpFormatter
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(self.getTimeOfDate), userInfo: nil, repeats: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer?.invalidate()
}
func getTimeOfDate() {
var curDate = Date()
timeLabel.text = formatter.string(from: curDate)
}
答案 1 :(得分:1)
将以下代码替换为ViewController代码,然后将iboutlet连接到showTimeLbl
class ViewController: UIViewController {
@IBOutlet weak var showTimeLbl: UILabel!
var timeCount:Int = 0
var timer:Timer!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if(timer != nil)
{
timer.invalidate()
}
timer = Timer(timeInterval: 1.0, target: self, selector: #selector(ViewController.timerDidFire), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: RunLoopMode.commonModes)
}
func timerDidFire()
{
timeCount += 1
showTimeLbl.text = NSString(format: "%02d:%02d:%02d", timeCount/3600,(timeCount/60)%60,timeCount%60) as String
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
timer?.invalidate()
timer = nil
}
}