Swift简单倒计时无法解决问题

时间:2016-05-01 22:13:46

标签: ios swift

我是编程新手,我打算在我的应用中添加倒计时。但是,当值低于10时,它不是09而只是9.我想把每个值都变为10,因为09,08。我的意思是0。

这是我的倒计时代码。我已经设法添加0分钟,但我不知道如何影响所有变量。提前致谢。

let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Hour, .Minute, .Month, .Year, .Day, .Second], fromDate: date)
_ = components.hour
_ = components.minute
_ = components.month
_ = components.year
_ = components.day
_ = components.second

let currentDate = calendar.dateFromComponents(components)

// I set here the due date. When the timer is supposed to finish
let userCalendar = NSCalendar.currentCalendar()

let competitionDate = NSDateComponents()
competitionDate.year = 2016
competitionDate.month = 5
competitionDate.day = 22
competitionDate.hour = 10
competitionDate.minute = 00
competitionDate.second = 00
let competitionDay = userCalendar.dateFromComponents(competitionDate)!

// I compare the two dates
competitionDay.timeIntervalSinceDate(currentDate!)

let dayCalendarUnit: NSCalendarUnit = ([. Month, .Day, .Hour, .Minute, . Second])

//I change here the seconds to hours,minutes and days
let CompetitionDayDifference = userCalendar.components( dayCalendarUnit, fromDate: currentDate!,toDate: competitionDay, options: [])
//Here I set the variable to our remaining time
let monthsLeft = CompetitionDayDifference.month
let daysLeft = CompetitionDayDifference.day
let hoursLeft = CompetitionDayDifference.hour
let minutesLeft = CompetitionDayDifference.minute
let secondsLeft = CompetitionDayDifference.second

if hoursLeft < 10 {
      allinoneLabel.text = String("0\(monthsLeft)  :  \(daysLeft)  :  0\(hoursLeft)  :  \(minutesLeft)  :  \(secondsLeft)")
}else {
     allinoneLabel.text = String("0\(monthsLeft)  :  \(daysLeft)  :  \(hoursLeft)  :  \(minutesLeft)  :  \(secondsLeft)")
}

0 个答案:

没有答案