2017-04-22 51 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) 
} 
} 
相關問題