我有一个标签,以12小时格式显示当前时间.
但是,每次分钟/小时更改时,它都不会更新/刷新时间.
我需要它在时间变化时自动将标签更改为当前时间.
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) }