如何使Swift倒计时

时间:2015-06-01 20:45:24

标签: swift timer

我正面临着制作计时器应用程序的困境,所以我认为现在我解决了它,我可以帮助其他人面对问题。所以基本上这个应用程序倒计时到当前时间的特定日期。由于堆栈溢出允许Q和A格式,我希望可以帮助您。请参阅注释以获得解释。

4 个答案:

答案 0 :(得分:10)

以下是我如何设法为特定NSDate创建倒数计时器的解决方案,因为SO允许Q和A样式答案。

// here we set the current date

 let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
    let hour = components.hour
    let minutes = components.minute
    let month = components.month
    let year = components.year
    let day = components.day



    let currentDate = calendar.dateFromComponents(components)

  // here we set the due date. When the timer is supposed to finish  

    let userCalendar = NSCalendar.currentCalendar()


    let competitionDate = NSDateComponents()
    competitionDate.year = 2015
    competitionDate.month = 6
    competitionDate.day = 21
    competitionDate.hour = 08
    competitionDate.minute = 00
    let competitionDay = userCalendar.dateFromComponents(competitionDate)!


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

    let dayCalendarUnit: NSCalendarUnit = (.CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute)

//here we change the seconds to hours,minutes and days
    let CompetitionDayDifference = userCalendar.components(
        dayCalendarUnit, fromDate: currentDate!, toDate: competitionDay,
        options: nil)
  //finally, here we set the variable to our remaining time  
    var daysLeft = CompetitionDayDifference.day
    var hoursLeft = CompetitionDayDifference.hour
    var minutesLeft = CompetitionDayDifference.minute

希望如果你面对与我一样的挣扎,帮助你们

答案 1 :(得分:7)

清理/更新已接受答案的最新Swift版本。

    // here we set the current date

    let date = NSDate()
    let calendar = Calendar.current

    let components = calendar.dateComponents([.hour, .minute, .month, .year, .day], from: date as Date)

    let currentDate = calendar.date(from: components)

    let userCalendar = Calendar.current

    // here we set the due date. When the timer is supposed to finish
    let competitionDate = NSDateComponents()
    competitionDate.year = 2017
    competitionDate.month = 4
    competitionDate.day = 16
    competitionDate.hour = 00
    competitionDate.minute = 00
    let competitionDay = userCalendar.date(from: competitionDate as DateComponents)!

    //here we change the seconds to hours,minutes and days
    let CompetitionDayDifference = calendar.dateComponents([.day, .hour, .minute], from: currentDate!, to: competitionDay)


    //finally, here we set the variable to our remaining time
    let daysLeft = CompetitionDayDifference.day
    let hoursLeft = CompetitionDayDifference.hour
    let minutesLeft = CompetitionDayDifference.minute

    print("day:", daysLeft ?? "N/A", "hour:", hoursLeft ?? "N/A", "minute:", minutesLeft ?? "N/A")

    //Set countdown label text
    countDownLabel.text = "\(daysLeft ?? 0) Days, \(hoursLeft ?? 0) Hours, \(minutesLeft ?? 0) Minutes"

答案 2 :(得分:4)

这对我有用。 让我感到困扰的唯一一件事就是它并没有真正倒计时,因为用户必须刷新页面才能重新计算。你可以看到它"计数"当用户在UITableView上向上和向下滚动单元格时,单元格会刷新视图。 另一件事是我在NSTimeZone的当前日期" GMT + 2:00"因为它适用于我的时间,但仅仅是因为我还没有弄清楚如何使用NSTimeZone设备。

    let releaseDate = "2015-05-02'T'22:00:00:000Z"
    let futureDateFormatter = NSDateFormatter()
    futureDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date: NSDate = futureDateFormatter.dateFromString(releaseDate!)!

    let currentDate = NSDate();
    let currentFormatter = NSDateFormatter();
    currentFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    currentFormatter.timeZone = NSTimeZone(abbreviation: "GMT+2:00")

    let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: currentDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))

    let countdown = "\(diffDateComponents.month) m: \(diffDateComponents.day) d: \(diffDateComponents.hour) h: \(diffDateComponents.minute) min"

答案 3 :(得分:1)

使用计时器计算的倒计时进行清理并更新,并且前导零字符串格式。

    let futureDate: Date = {
        var future = DateComponents(
            year: 2020,
            month: 1,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0
        )
        return Calendar.current.date(from: future)!
    }()

    var countdown: DateComponents {
        return Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: futureDate)
    }

    @objc func updateTime() {
        let countdown = self.countdown //only compute once per call
        let days = countdown.day!
        let hours = countdown.hour!
        let minutes = countdown.minute!
        let seconds = countdown.second!
        countdownLabel.text = String(format: "%02d:%02d:%02d:%02d", days, hours, minutes, seconds)
    }

    func runCountdown() {
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }