简体   繁体   English

SwiftUI iOS 14 小部件倒计时

[英]SwiftUI iOS 14 Widget CountDown

I have a iOS 14 widget with a Countdown我有一个带有倒计时的 iOS 14 小部件

Text(foo, style: .timer)

How can I change text color to red when the time is less than 1 minute?当时间少于 1 分钟时,如何将文本颜色更改为红色?

Here is how you can create a countdown for 1 minute with the text color changing to red when it's 10 seconds left.以下是如何创建1 minute的倒计时,并在剩余10 seconds时将文本颜色更改为红色。 When the time is over the countdown starts again.时间一过,倒计时又开始了。

  1. Create an Entry where displayDate is the total time (here 1 minute):创建一个条目,其中displayDate是总时间(此处为 1 分钟):
struct SimpleEntry: TimelineEntry {
    let date: Date
    let displayDate: Date
    var isDateClose = false
}
  1. In your Provider create two Entries - one for the standard color and one for the isClose color (here red ):在您的 Provider 中创建两个条目 - 一个用于标准颜色,一个用于isClose颜色(此处为red ):
struct SimpleProvider: TimelineProvider {
    ...

    func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) {
        let currentDate = Date()
        let firstDate = Calendar.current.date(byAdding: .second, value: 50, to: currentDate)!
        let secondDate = Calendar.current.date(byAdding: .second, value: 60, to: currentDate)!

        let entries = [
            SimpleEntry(date: currentDate, displayDate: secondDate),
            SimpleEntry(date: firstDate, displayDate: secondDate, isDateClose: true),
        ]

        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
}
  1. Use it in your view:在您的视图中使用它:
struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry

    var body: some View {
        Text(entry.displayDate, style: .timer)
            .foregroundColor(entry.isDateClose ? .red : .primary)
    }
}

Here is a GitHub repository with different Widget examples including the Countdown Widget.这是一个GitHub 存储库,其中包含不同的 Widget 示例,包括 Countdown Widget。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM