从主屏幕加载应用程序时调用什么函数?

What function gets called when loading app from homescreen?

我希望能够根据一天中的时间更改我的应用程序的背景颜色。我相信解决这个问题的方法是说如果小时分量大于任何数字,将背景设置为夜间背景,否则就是白天背景。

为了测试我担心的是什么,我扔了

timeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .FullStyle)

变成viewDidLoad。这显示了应用程序加载的时间。如果我终止应用程序并完全重新加载它,这显然也会不断更新。

但是,如果用户转到主屏幕或转到其他应用,则返回此时间不会更新。它将显示应用程序首次加载的时间。只有用户彻底杀掉这个明显靠不住的app,才会显示正确的时间。

所以在我的示例中,如果我的 "switch to nighttime time" 是下午 5 点,如果用户在 4:30 处加载,然后转到主屏幕,在下午 5 点加载应用程序,则什么都不会已更改,因为存储时间仍为 4:30.

我尝试将代码放入 viewDidAppear 中,但没有任何改变。

当应用程序从主屏幕加载或从其他应用程序返回时,运行 代码是什么?

你会想看看使用 NSCalendar 为此:

let currentDate = NSDate() // You can input the custom as well 
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate:  NSDate())
let currentHour = components.hour // You can play around with the ""components""

下面的方法就是你想要的:

applicationDidBecomeActive: 每次用户打开应用程序时都会调用它。

每次用户进入您的应用程序时,您的应用程序委托中的方法 -applicationWillEnterForeground: 都会被调用。

您想结束 UIApplicationDidBecomeActiveNotification 活动。试试这个:

override func viewDidLoad() 
{
    super.viewDidLoad()

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "applicationDidBecomeActive:",
        name: UIApplicationDidBecomeActiveNotification,
        object: nil)
}

func applicationDidBecomeActive(notification: NSNotification) 
{
    // do something when the app is active again.
    timeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .NoStyle, timeStyle: .FullStyle)
}