计时器倒计时快速跳过秒并暂停

时间:2015-09-18 19:11:16

标签: ios swift nstimer

我正在为我正在更新的应用制作倒计时组件。我终于让它工作但是当它在我的模拟器上或当我通过我的手机运行时,它陷入困境并跳过秒,有时会冻结我的屏幕并且不允许我改变视图等。这是我的代码。我很好奇为什么会这样。

提前谢谢!

class CountdownViewController: UIViewController {

@IBOutlet weak var days: UILabel!
@IBOutlet weak var hours: UILabel!
@IBOutlet weak var minutes: UILabel!
@IBOutlet weak var seconds: UILabel!

var timer:NSTimer!

func reloadData(){
    self.viewDidLoad()
}

override func viewDidLoad() {
    super.viewDidLoad()

    self.timer = NSTimer(timeInterval: 0.5, target: self, selector: Selector("reloadData"), userInfo: nil, repeats: true)

    NSRunLoop.currentRunLoop().addTimer(self.timer, forMode: NSRunLoopCommonModes)

    self.canDisplayBannerAds = true

    // here we set the current date
    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay | .CalendarUnitSecond, fromDate: date)
    let hour = components.hour
    let minute = components.minute
    let month = components.month
    let year = components.year
    let day = components.day
    let second = components.second

    let currentDate = calendar.dateFromComponents(components)

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

    let userCalendar = NSCalendar.currentCalendar()

    let electionDate = NSDateComponents()
    electionDate.year = 2016
    electionDate.month = 11
    electionDate.day = 08
    electionDate.hour = 00
    electionDate.minute = 00
    electionDate.second = 00
    let electionDay = userCalendar.dateFromComponents(electionDate)!


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

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

    //here we change the seconds to hours,minutes and days
    let electionDayDifference = userCalendar.components(dayCalendarUnit, fromDate: currentDate!, toDate: electionDay,options: nil)

    //finally, here we set the variable to our remaining time
    var daysLeft = electionDayDifference.day
    var hoursLeft = electionDayDifference.hour
    var minutesLeft = electionDayDifference.minute
    var secondsLeft = electionDayDifference.second

    days.text = String(daysLeft)
    hours.text = String(hoursLeft)
    minutes.text = String(minutesLeft)
    seconds.text = String(secondsLeft)

}

2 个答案:

答案 0 :(得分:3)

您每0.5秒向RunLoop添加越来越多的计时器。它们都被立即解雇,导致性能随着时间的推移而降低。您需要将// here we set the current date评论下的所有代码移至reloadData函数并从那里删除self.viewDidLoad(),一切都应该没问题。您的计时器只会安排一次,并会每0.5秒重复调用一次reloadData(因为您使用repeats: true参数创建了它。)

答案 1 :(得分:0)

不要调用viewDidLoad()

它是一种委托方法,由视图控制器调用(一次),并指定用于设置一次。

在自定义函数中触发定时器后,将执行代码。 没有必要一次又一次地创建计时器,将参数repeats设置为true会定期调用选择器。