只是想知道是否有一种方法可以在 SwiftUI 的 Text UI 中为 DateStyle comp 应用自定义格式。例如,就像使用 DateFormatter 时一样,只是分钟或秒。我想显示小部件的动态日期,但它只提供有限数量的选项。这是为什么?有人找到解决方法吗?
Apple 在此处详细介绍了显示动态日期:https ://developer.apple.com/documentation/widgetkit/keeping-a-widget-up-to-date
我正在为 ios 14 Home Widget 开发一个应用程序,在显示当前时间(数字时钟)时遇到一个问题,即该小部件没有每秒更新。众所周知,苹果不允许每秒触发时间线,有没有其他方法可以实时更新显示当前时间?
我尝试了这些方法,但没有按预期工作
class NetworkManager: ObservableObject {
@Published var dateIs = Date()
init() {
startTimer() // fetch data must be called at least once
}
private func startTimer() {
let t = RepeatingTimer(timeInterval: 3)
t.eventHandler = {
DispatchQueue.main.async() {
// your UI update code
print("Timer Fired")
self.dateIs = Date()
WidgetCenter.shared.reloadAllTimelines() // reload timelines
}
if(false){ //I know this makes no sense, but it works. Go figure...
t.suspend()
}
}
t.resume()
}
}
struct Provider: TimelineProvider { …Run Code Online (Sandbox Code Playgroud) 我有一个工作时钟小部件。为了实现这一目标,我创建了一个每天更新一次的时间表。
func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
let midnight = Calendar.current.startOfDay(for: Date())
let nextMidnight = Calendar.current.date(byAdding: .day, value: 1, to: midnight)!
let entries = [SimpleEntry(date: midnight)]
let timeline = Timeline(entries: entries, policy: .after(nextMidnight))
completion(timeline)
}
Run Code Online (Sandbox Code Playgroud)
小部件显示时钟如下:
var body: some View {
VStack {
Text(entry.date, style: .timer)
}
}
Run Code Online (Sandbox Code Playgroud)
我选择了这种方法,而不是每分钟创建一个条目时间线,因为我在文档中读到,系统不承诺按要求更新小部件,而是根据预算。
标签显示如下:
14:30:25
我怎样才能让它显示
改为下午 2:30