如何根据一天中的时间更改UIView背景图像(swift)


let homepageDay = UIImage(cgImage:  "Homepage Day" as! CGImage)
let homepageNight = UIImage(cgImage: "Homepage Night" as! CGImage)
let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)
switch hour
{
// hours 1 to 6
case 1...6: homepageDay. = UIImage
//self.backgroundImage = homepageNight
break
// hours 7 to 18

想要根据一天中的时间更改背景图像

在变量中获取当前日期的小时数,如:

let hour = Calendar.current.component(.hour, from: Date())

现在将其传递到switch语句并更改图像。

您的Swift Statement将是这样的(根据需要更改图像(:

switch hour {
case 1...6: 
yourImageView.image = homepageNight
case 7...18: 
yourImageView.image = homepageNight
default:
yourImageView.image = homepageNight
}

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

很乐意帮忙!

如果您只需要获取当前小时并知道它是上午还是下午,您可以使用以下内容:

let formatter = DateFormatter()
formatter.dateFormat = "hh a" // "a" prints "pm" or "am"
let hourString = formatter.string(from: Date()) // "12 AM"

因此,在此之后,您只需要应用正确的图像间隔时间来获得字符串值。

最新更新