В настоящее время есть таймер, который отсчитывает оставшееся время до изменения времени каждую минуту. У меня работает обратный отсчет, но интересно, как уменьшить отображаемый обратный отсчет, чтобы прикрепить переменную @State. Но, честно говоря, поскольку это виджет, мне кажется, что это невозможно. Код ниже
struct DigitalClockView: View {
let entry: DigitalClockEntry
let components: DateComponents
let futureDate: Date
var currentTime: String {
let time = entry.date
let timeFormatter = DateFormatter()
timeFormatter.dateFormat = "H:mm"
return timeFormatter.string(from: time)
}
@State var countDown: String = ""
init(entry: DigitalClockEntry) {
self.entry = entry
let difference = 60 - Calendar.current.component(.second, from: entry.date)
self.components = DateComponents(second: difference)
self.futureDate = Calendar.current.date(byAdding: components, to: entry.date)!
}
var body: some View {
VStack(alignment: .center) {
Text(futureDate, style: .timer)
Text(currentTime)
}
}
}
extension Date {
func adding(
_ component: Calendar.Component,
value: Int,
in calendar: Calendar = .current
) -> Self {
calendar.date(byAdding: component, value: value, to: self)!
}
}
/// Поставщик
struct DigitalClockProvider: TimelineProvider {
private let placeholderEntry = DigitalClockEntry(
date: Date(),
futureDate: Date()
)
func placeholder(in context: Context) -> DigitalClockEntry{
placeholderEntry
}
func getSnapshot(in context: Context, completion: @escaping (DigitalClockEntry) -> ()) {
completion(DigitalClockEntry(date: Date(), futureDate: Date()))
}
func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) {
let currentDate = Date()
let entryDate = Calendar.current.date(byAdding: .second, value: 60, to: currentDate)!
let entries = [ DigitalClockEntry(date: currentDate, futureDate: entryDate) ]
let timeline = Timeline(entries: entries, policy: .after(currentDate))
completion(timeline)
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... e-variable