在NSDate() - Swift中每秒更新一次时间函数

时间:2014-10-30 06:17:49

标签: ios swift

我有一个功能,让我有机会打开应用程序,但我不希望它是静态的,我希望它是动态的,每秒更新一次。我认为它处于循环中,但我不知道如何去做。做一个循环可以工作,但如果你有更好的方法,请回答。这是我的功能:

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;
    } 

问题:如何使此功能动态化?所以它每秒都会更新而不是静态标签。

如果您有任何疑问,请在下方发表评论。

1 个答案:

答案 0 :(得分:2)

试试这个。您需要添加标签和按钮并将它们连接到textLabel并启动IBAction。你可以修改它来增加小时数(这里只需几分钟/秒),并在你需要的地方添加一个timer.invalidate()。

import UIKit

class ViewController: UIViewController {

    @IBOutlet var timeLabel: UILabel!

    @IBAction func start(sender: AnyObject) {
        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(":")
        }
    }

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

    override func viewDidLoad() {
        super.viewDidLoad()

    }

    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;
    }
}