【问题标题】:Change background with specific Hour and minutes in swift [closed]快速更改特定小时和分钟的背景[关闭]
【发布时间】:2019-04-29 17:10:34
【问题描述】:

嘿,可以使用小时和分钟更改应用程序中的背景图像吗?例如 7:30 的日出,它会将背景更改为日出图片,时间流逝它也会在特定的时间和分钟变为早晨。如果可以的话如何快速设置。谢谢你

【问题讨论】:

  • 什么背景?您的应用程序或主屏幕中有什么?你的具体问题是什么?现在这个范围太广了。请edit您的问题(没有 cmets)提供有关您的问题的更具体细节。
  • 信不信由你,即使在 iOS 和 Swift 中,OOP 的概念仍在发挥作用。所以像对待任何其他工程问题一样对待这个问题,一步一步地进行。我可能首先从谷歌搜索“特定时间的快速呼叫功能”之类的东西开始......然后从那里开始。
  • 什么背景?不清楚的问题请编辑您的问题
  • 嘿@rmaddy 一个应用程序的背景,我只是改变我的问题

标签: ios swift date datetime nsdate


【解决方案1】:

AppDelgate 中的以下方法将完成这项工作。 func applicationWillEnterForeground(_ application: UIApplication) { // 作为从后台到非活动状态转换的一部分调用;在这里您可以撤消在进入后台时所做的许多更改。 }

这将在应用程序打开/启动时被调用。根据时间更改应用的背景。

【讨论】:

  • change the app's background according to the time 这正是 OP 的要求,而你没有回答。
【解决方案2】:

你可以这样做:

func setupTimer(hour: Int, minute: Int, second: Int, newColor: UIColor){
    let calendar = Calendar.current.date(bySettingHour: hour, minute: minute, second: second, of: Date())

    let timer = Timer(fireAt: calendar!, interval: 0, target: self, selector: #selector(changeBackground(_:)), userInfo: UIColor.gray, repeats: true)
    RunLoop.main.add(timer, forMode: .common)

}



@objc func changeBackground(_ timer: Timer?){
    if let newColor = timer?.userInfo as? UIColor {

        DispatchQueue.main.async {
        self.view.backgroundColor = newColor
        }
    }
}

【讨论】:

  • 这是最简单的部分。您忽略了知道将什么传递给 setupTimer 的困难部分。
  • @rmaddy 是的,但是这个问题没有包含太多细节,我认为问题的作者只是不知道如何在后台更改某些内容并跳过前面的部分,因为你的豪宅是困难的部分,需要几个步骤,包括实现 CoreLocation、API 请求、JSON 解析......
【解决方案3】:

如果您说的是更改 HomeScreen 上的 iOS 背景,则不是。与 iOS 相比,Swift 并没有给你那么多的能力。 但是,如果您正在谈论更改应用程序中的背景以反映一天中的时间,那么这绝对是可能的。解决这个问题的最佳方法是使用 AppDelegate.swift 文件中名为

的函数打开应用程序后立即检查时间
applicationDidBecomeActive

在那里,您需要捕获日期并将其设置为全局变量(如果您不熟悉,请参阅here 了解有关如何执行此操作的更多信息)

将 Date 设置为全局变量后,您需要告诉应用程序在加载视图时更改背景。这只是代码实际外观的伪代码,但我希望它有所帮助:

let sunRiseTime : Date = //insert date you would like the background to change here.
let noon : Date = //insert date for noon here
let sunriseBackgroundImage : UIImage = //insert image you would like for the sunrise here
let noonBackgroundImage : UIImage = //insert image you would like for noon here.

if(dateGlobalVariable >= sunriseTime){
self.backgroundImage = sunriseBackgroundImage
}else if(dateGlobalVariable >= noon{
self.backgroundImage = noonBackgroundImage
} 
//continue this for as many images as you have.

希望这会有所帮助!如果您有任何问题,请告诉我!

【讨论】:

  • 仅供参考 - 无法更改主屏幕背景与 Swift 无关。你也不能在 Objective-C 中做到这一点。
  • 此代码不会在用户使用应用程序时更改背景。只有当他们离开并回来时才有效。
  • @cdunn2013 感谢您的回复,我很沮丧在正确的时间更改我的应用程序中的背景图像。我只能通过使用计时器的 Hour 来做到这一点,但这不是我想要的,除非你给我一个好的解决方案。再次感谢!!有问题再问你☺️
  • @rmaddy 正确,我忘了提一下,将您放入 AppDelegate 中的相同函数放入 ViewDidLoad 以传递全局变量是一个好习惯。
  • @ferryawijayanto 听起来不错,如果您需要更多帮助,请告诉我,我会一对一帮助您。
猜你喜欢
  • 1970-01-01
  • 2017-02-06
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 2016-02-27
  • 1970-01-01
  • 2013-07-22
  • 1970-01-01
相关资源
最近更新 更多