在午夜更新ContentView中的变量

问题描述 投票:0回答:1

我的 ContentView 文件中有以下变量

let DOY = getDayOfYear()
let DRNoW = daysinyear()
let WN = weekNumber()
let DN = dayNumber()

并使用以下功能:

func getDayOfYear() -> Int {
    let date = Date() // now
    let cal = Calendar.current
    let day1 = cal.ordinality(of: .day, in: .year, for: date)!

    return day1
}

我希望变量在午夜更新 ContentView 中。

我该如何实现它?

macos swiftui
1个回答
0
投票

您可以订阅 UIApplicationSignificantTimeChangeNotification

struct ContentView: View {
    var body: some View {
        ...
        .onReceive(NotificationCenter.default
            .publisher(for: UIApplication.significantTimeChangeNotification)) { (output) in
            // Update variables at midnight here
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.