2017-04-22 48 views

回答

1

你的问题的部分没有什么意义:

“我应该在哪里放一个日期实例,我应该怎么句柄调用它,以获得当前的日期?”

日期实例记录一个固定的时间。代码

let date = Date() 

将在它被调用的时刻记录当前日期,而不会改变。如果您的程序明天仍在运行,那么该日期现在将非常“过时”。

您应该在任何需要当前日期的时候使用表达式Date()

+0

我不知道你可以使用Date()这样的。谢谢! –

1

”我应该在哪里放一个Date实例,我应该如何处理它以便获取当前日期?“ 在您当前的View Controller中已经足够了。只要VC还活着,它就对你的Date对象有很强的参考。

“我应该用日期实例做单身吗?” 号如果你需要保持日期相关,你需要触发一个计时器(假设1分钟 所以它不会打扰太多),将保持更新UI

“我应该把这个例如在一个日期AppDelegate的函数为了更新应用程序未被使用时的当前日期?“ 不,您可以收到通知,并通过它们知道何时将计时器向上或向下。 见代码

class ViewController: UIViewController{ 
// label to hold the date 
@IBOutlet var dateLabel: UILabel! 

// timer to keep it updated 
var fetchTimer: Timer! 

override func viewDidLoad() 
{ 
    super.viewDidLoad() 

    // set date immediately (dont wait for timer) 
    viewDidEnterForeground() 

    // follow Foreground so when we re-enter, timer will launch again 
    NotificationCenter.default.addObserver(self, 
              selector: #selector(ViewController.viewDidEnterForeground), 
              name:NSNotification.Name.UIApplicationWillEnterForeground, 
              object: nil) 

    // follow background for invalidating timer 
    NotificationCenter.default.addObserver(self, 
              selector: #selector(ViewController.viewDidEnterBackground), 
              name:NSNotification.Name.UIApplicationDidEnterBackground, 
              object: nil) 
} 
// on each entry - set date and fire timer 
func viewDidEnterForeground() 
{ 
    setDate() 

    fetchTimer = Timer.scheduledTimer(timeInterval: 60.0, 
             target: self, 
             selector: #selector(timerFunc), 
             userInfo: nil, 
             repeats: true) 
} 
func viewDidEnterBackground() 
{ 
    fetchTimer.invalidate() 
} 
func timerFunc() 
{ 
    setDate() 
} 
func setDate() 
{ 
    let date = Date() 

    let formatter = DateFormatter() 
    formatter.dateFormat = "dd.MM.yyyy" 

    // "22.04.2017" 
    let dateFormatString = formatter.string(from: date) 

    DispatchQueue.main.async 
    { 
     self.dateLabel.text = dateFormatString 
    } 
} 
deinit 
{ 
    NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationWillEnterForeground, object: nil) 

    NotificationCenter.default.removeObserver(self, name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil) 
} 
} 
相关问题