当命中零时停止 SwiftUI 小部件的相对文本字段计数器? [英] Stopping a SwiftUI Widget's relative textfield counter when hits zero?

查看:26
本文介绍了当命中零时停止 SwiftUI 小部件的相对文本字段计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个小部件,它有一个从日期开始倒计时的文本字段:

I am creating a Widget that has a textfield that counts down from a date like so:

Text(endDate, style: .relative)

这很好用,但是作为它的相对值,一旦它达到零,它就会继续倒数,因为 endDate 变成了过去.

This works fine, however as its relative, once it hits zero, it will continue to count back up again as the endDate becomes in the past.

有没有办法在文本达到零时终止文本?还是我必须用计时器重建这个功能?

Is there a way to terminate the text when it hits zero? Or do I have to rebuild this feature with a timer?

我需要做的就是从开始日期到结束日期倒计时,然后使文本字段无效或显示一条消息.

All I need to do is count down from a start date to and end date then invalidate the text field or show a message.

推荐答案

这里介绍了如何创建倒计时并在时间结束时显示一些其他文本.

Here is how you can create a countdown and when the time is over display some other text.

  1. 创建一个条目,其中 endDate 是可选的 - 如果它是 nil,则表示倒计时结束:
  1. Create an Entry where endDate is optional - if it's nil it means that the countdown is over:

struct SimpleEntry: TimelineEntry {
    let date: Date
    var endDate: Date?
}

  1. 在您的 Provider 中创建两个条目 - 一个用于倒计时时间,一个用于倒计时结束:
  1. In your Provider create two Entries - one for the countdown time and one for when the countdown is over:

struct SimpleProvider: TimelineProvider {
    ...

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

        let entries = [
            SimpleEntry(date: currentDate, endDate: endDate),
            SimpleEntry(date: endDate),
        ]

        let timeline = Timeline(entries: entries, policy: .never)
        completion(timeline)
    }
}

  1. 在您的视图中使用它:

struct WidgetEntryView: View {
    var entry: Provider.Entry

    var body: some View {
        if let endDate = entry.endDate {
            Text(endDate, style: .relative)
        } else {
            Text("Timer finished")
        }
    }
}

这篇关于当命中零时停止 SwiftUI 小部件的相对文本字段计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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