我是Swift和iOS开发的新手。我正在尝试特定日期的倒计时。 我的iOS倒计时应用程序在零后计数为负数。我想停在零。我该如何解决?
let currentDate = Date()
let dateFormatter = DateFormatter()
let userCalendar = Calendar.current
let requestedComponent: Set<Calendar.Component> = [.day,.hour,.minute,.second]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)
timer.fire()
}
func printTime()
{
dateFormatter.dateFormat = "dd/MM/yy hh:mm:ss"
let startTime = Date()
let endTime = dateFormatter.date(from: "11/03/18 10:00:00")
let time = userCalendar.dateComponents(requestedComponent, from: startTime, to: endTime!)
dayLabel.text = "\(time.day!)"
hourLabel.text = "\(time.hour!)"
minuteLabel.text = "\(time.minute!)"
secondLabel.text = "\(time.second!)"
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
答案 0 :(得分:1)
尝试更改:
dayLabel.text = "\(time.day!)"
hourLabel.text = "\(time.hour!)"
minuteLabel.text = "\(time.minute!)"
secondLabel.text = "\(time.second!)"
为:
if startTime < endTime {
dayLabel.text = "\(time.day!)"
hourLabel.text = "\(time.hour!)"
minuteLabel.text = "\(time.minute!)"
secondLabel.text = "\(time.second!)"
} else {
dayLabel.text = "0"
hourLabel.text = "0"
minuteLabel.text = "0"
secondLabel.text = "0"
}
根据您的情况,您可能希望使用timer.invalidate()
停止计时器,如下所示:
...
var timer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(printTime), userInfo: nil, repeats: true)
timer?.fire()
}
func printTime() {
...
} else {
...
timer?.invalidate()
}
}
答案 1 :(得分:0)
pandas