如何在文本视图中停止计时器? [英] How to stop timer in Text view?

查看:29
本文介绍了如何在文本视图中停止计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以在 SwiftUI 中将日期传递给 Text(),然后使用 style 参数将其格式化为计时器.然而,这样的倒计时永远不会停止,它只是在零后不断增加.如何让它停在0?

It is possible to pass a date to Text() in SwiftUI, then format it as a timer using the style argument. However, a countdown like this never stops, it just keeps incrementing after zero. How to make it stop at 0?

func nextRollTime(in seconds: Int) -> Date {
    let date = Calendar.current.date(byAdding: .second, value: seconds, to: Date())
    return date ?? Date()
}

上面是我用来开始倒计时的函数,然后我按如下方式传递:

Above is the function I use to start a countdown, then I pass it as follows:

Text(nextRollTime(in: 20), style: .timer)

推荐答案

这是一个可能的方法的演示 - 作为 .timer 从现在开始永远运行(按设计),想法是替换一旦指定的时间段结束,它就会带有常规文本.

Here is a demo of possible approach - as .timer run from now for ever (by design), the idea is to replace it with regular text once specified period is over.

使用 Xcode 12b3/iOS 14 测试.

Tested with Xcode 12b3 / iOS 14.

struct DemoView: View {
    @State private var run = false

    var body: some View {
        VStack {
            if run {
                Text(nextRollTime(in: 10), style: .timer)
            } else {
                Text("0:00")
            }
        }
        .font(Font.system(.title, design: .monospaced))
        .onAppear {
            self.run = true
        }
    }

    func nextRollTime(in seconds: Int) -> Date {
        let date = Calendar.current.date(byAdding: .second, value: seconds, to: Date())
        DispatchQueue.main.asyncAfter(deadline: .now() + Double(seconds)) {
            self.run = false
        }
        return date ?? Date()
    }
}

这篇关于如何在文本视图中停止计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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