为什么 significantTimeChangeNotification 没有发出(或没有收到?)
Why is significantTimeChangeNotification not emitted (or not received?)
我是 Swift 的新手。出于学习目的,我正在创建一个小的倒计时应用程序(直到日期 X 的天数)。
这些倒计时显示在列表中。列表中的单个倒计时由以下视图表示。
struct CountdownRow: View {
@State private var remainingDays: Int = 0
@State private var progress: Float = 0.0
var countdown: Countdown
var body: some View {
VStack{
HStack {
Text(countdown.name)
.font(.subheadline)
.multilineTextAlignment(.leading)
.padding(10)
Spacer()
Text(String(remainingDays))
.font(.headline)
.padding(10)
}
ProgressView(value: progress)
.padding(10)
}
.onAppear {
remainingDays = countdown.getRemainingDays()
progress = countdown.getProgress()
}
.onReceive(NotificationCenter.default.publisher(for:
UIApplication.significantTimeChangeNotification),
perform: { _ in
remainingDays = countdown.getRemainingDays()
progress = countdown.getProgress()
})
}
}
我想在午夜更新每个倒计时的剩余天数。但是当时间从 23:59 变为 0:00 时,.onReceive 修饰符不会触发。
接收其他通知(例如 UIApplication.willEnterForegroundNotification)却按预期工作。
为什么这个特定的通知在午夜没有发出(或接收到)?
根据 apple 的文档,它应该在午夜发出。
谢谢!
如果应用程序在前台,它会在午夜发出。您的应用程序在午夜时分出现在前台吗?否则,您应该检查 return 到前台的时间并相应地更新。
所有 NSNotifications 都是如此。如果您的应用程序被暂停,则不会收到它们。这不是 significantTimeChangeNotification 的特殊情况。
willEnterForegroundNotification 可能看起来很特殊,但它只会在您的应用已经重新启动的情况下发送。
就是说,我强烈建议重新设计它,使 Countdown 成为一个 ObservableObject,并在适当的时间更新自身(通过观察 significantTimeChangeNotification 和 willEnterForegroundNotification)。然后,您可以将 remainingDays
和 progress
绑定到它,而无需在视图上使用 onAppear
或 onReceive
。
我是 Swift 的新手。出于学习目的,我正在创建一个小的倒计时应用程序(直到日期 X 的天数)。 这些倒计时显示在列表中。列表中的单个倒计时由以下视图表示。
struct CountdownRow: View {
@State private var remainingDays: Int = 0
@State private var progress: Float = 0.0
var countdown: Countdown
var body: some View {
VStack{
HStack {
Text(countdown.name)
.font(.subheadline)
.multilineTextAlignment(.leading)
.padding(10)
Spacer()
Text(String(remainingDays))
.font(.headline)
.padding(10)
}
ProgressView(value: progress)
.padding(10)
}
.onAppear {
remainingDays = countdown.getRemainingDays()
progress = countdown.getProgress()
}
.onReceive(NotificationCenter.default.publisher(for:
UIApplication.significantTimeChangeNotification),
perform: { _ in
remainingDays = countdown.getRemainingDays()
progress = countdown.getProgress()
})
}
}
我想在午夜更新每个倒计时的剩余天数。但是当时间从 23:59 变为 0:00 时,.onReceive 修饰符不会触发。 接收其他通知(例如 UIApplication.willEnterForegroundNotification)却按预期工作。
为什么这个特定的通知在午夜没有发出(或接收到)? 根据 apple 的文档,它应该在午夜发出。
谢谢!
如果应用程序在前台,它会在午夜发出。您的应用程序在午夜时分出现在前台吗?否则,您应该检查 return 到前台的时间并相应地更新。
所有 NSNotifications 都是如此。如果您的应用程序被暂停,则不会收到它们。这不是 significantTimeChangeNotification 的特殊情况。
willEnterForegroundNotification 可能看起来很特殊,但它只会在您的应用已经重新启动的情况下发送。
就是说,我强烈建议重新设计它,使 Countdown 成为一个 ObservableObject,并在适当的时间更新自身(通过观察 significantTimeChangeNotification 和 willEnterForegroundNotification)。然后,您可以将 remainingDays
和 progress
绑定到它,而无需在视图上使用 onAppear
或 onReceive
。