更新获得确切时间的函数 - Swift

时间:2014-11-07 17:03:36

标签: ios xcode swift

我有一个能够获得确切时间的函数。这是代码:

func getTime() {
    var date = NSDate()
    var outputFormat = NSDateFormatter()
    outputFormat.locale = NSLocale(localeIdentifier:"en_US")
    outputFormat.dateFormat = "HH:mm:ss"
    println(outputFormat.stringFromDate(date))
}


getTime()

它获取确切的时间但不会每秒更新。我有一个函数可以获得视图加载时的确切时间,但它会在系统可以计数并且系统无法跟上准确时间时计数,并且落后几秒钟。

什么功能会每秒实时更新

获取时间的代码

var time = [String]()
var startTime = NSTimeInterval()

//This is the viewDidLoad Function
override func viewDidLoad() {
    super.viewDidLoad()
    handler(theDatePicker)
    var timer = NSTimer()
    if !timer.valid {
        let selector : Selector = "countTime"
        timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target:self, selector: selector, userInfo: nil, repeats: true)
        startTime = NSDate.timeIntervalSinceReferenceDate()
    }
    let timeNow = timeNowString() as String
    for item in timeNow {
        time = timeNow.componentsSeparatedByString(":")
    }

    theDatePicker.addTarget(self, action: Selector("handler:"), forControlEvents: UIControlEvents.ValueChanged)

    func getTime() {
        var date = NSDate()
        var outputFormat = NSDateFormatter()
        outputFormat.locale = NSLocale(localeIdentifier:"en_US")
        outputFormat.dateFormat = "HH:mm:ss"
        timeLabel.text = (outputFormat.stringFromDate(date))
    }






}


func countTime() {
    var currentTime = NSDate.timeIntervalSinceReferenceDate()
    var elapsedTime: NSTimeInterval = currentTime - startTime
    var adjustedTime = Int(elapsedTime) + 3600*time[0].toInt()! + 60*time[1].toInt()! + time[0].toInt()!

    var hours = Int(Double(adjustedTime)/3600.0)
    let minutes = Int(Double(adjustedTime - hours*3600)/60.0)
    let seconds = adjustedTime - hours*3600 - minutes*60

    let startHours  = hours > 9 ? String(hours):"0" + String(hours)
    let startMinutes  = minutes > 9 ? String(minutes):"0" + String(minutes)
    let startSeconds  = seconds > 9 ? String(seconds):"0" + String(seconds)

    //timeLabel.text = "\(startHours):\(startMinutes):\(startSeconds)"
}


func timeNowString() -> NSString {
    let date = NSDate()
    var outputFormat = NSDateFormatter()
    outputFormat.locale = NSLocale(localeIdentifier:"en_US")
    outputFormat.dateFormat = "HH:mm:ss"
    let timeString = outputFormat.stringFromDate(date)
    return timeString;
}

viewDidAppear功能

override func viewDidAppear(animated: Bool) {
        func getTime() {
            var date = NSDate()
            var outputFormat = NSDateFormatter()
            outputFormat.locale = NSLocale(localeIdentifier:"en_US")
            outputFormat.dateFormat = "HH:mm:ss"
            timeLabel.text = (outputFormat.stringFromDate(date))
        }

        let timer = NSTimer(timeInterval: 1, target: self, selector: "getTime", userInfo: nil, repeats: true)

        timeLabel.text = "\(timer)"
    }

1 个答案:

答案 0 :(得分:3)

编辑: 您的计时器设置为.01秒,而不是每1秒。

如果您在初始化NSDate()(即当前时间)时系统滞后几秒,则代码中还有其他问题。确保你的主线程。您的代码工作正常,请检查您调用该函数的位置。如果在viewDidAppear中调用了getTime()函数,那么它将完全出现在视图中,时间将反映出来。设置NSTimer为您希望刷新发生的时间,并将操作设置为getTime()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    var timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("getTime"), userInfo: nil, repeats: true)
    // This will call the getTime function every second which in turns updates your label
}

func getTime() {
    var date = NSDate()
    var outputFormat = NSDateFormatter()
    outputFormat.locale = NSLocale(localeIdentifier:"en_US")
    outputFormat.dateFormat = "HH:mm:ss"
    timeLabel.text = (outputFormat.stringFromDate(date))  // This line here will update your timeLabel with the current time every second
}