SwiftUI iOS 14 小部件倒计时 [英] SwiftUI iOS 14 Widget CountDown

查看:45
本文介绍了SwiftUI iOS 14 小部件倒计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有倒计时功能的 iOS 14 小部件

I have a iOS 14 widget with a Countdown

Text(foo, style: .timer)

当时间少于 1 分钟时,如何将文本颜色更改为红色?

How can I change text color to red when the time is less than 1 minute?

推荐答案

这里是如何创建 1 分钟 的倒计时,当 10 秒时,文本颜色变为红色 离开了.时间一过,倒计时又开始了.

Here is how you can create a countdown for 1 minute with the text color changing to red when it's 10 seconds left. When the time is over the countdown starts again.

  1. 创建一个条目,其中 displayDate 是总时间(此处为 1 分钟):
  1. Create an Entry where displayDate is the total time (here 1 minute):

struct SimpleEntry: TimelineEntry {
    let date: Date
    let displayDate: Date
    var isDateClose = false
}

  1. 在您的 Provider 中创建两个条目 - 一个用于 standard 颜色,一个用于 isClose 颜色(此处为 red):
  1. In your Provider create two Entries - one for the standard color and one for the isClose color (here 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. 在您的视图中使用它:

struct SimpleWidgetEntryView: View {
    var entry: SimpleProvider.Entry

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


这是一个 GitHub 存储库,其中包含不同的 Widget 示例,包括倒计时小部件.


Here is a GitHub repository with different Widget examples including the Countdown Widget.

这篇关于SwiftUI iOS 14 小部件倒计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆