How to stop timer in Text view?

前端 未结 1 410
野性不改
野性不改 2020-12-21 14:26

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,

相关标签:
1条回答
  • 2020-12-21 14:52

    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.

    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()
        }
    }
    
    0 讨论(0)
提交回复
热议问题