TimeView.swift (2552B)
1 /* 2 * This file is part of GNU Taler, ©2022-26 Taler Systems S.A. 3 * See LICENSE.md 4 */ 5 /** 6 * @author Marc Stibane 7 */ 8 import SwiftUI 9 10 struct TimeView: View { 11 let title: String 12 let seconds: Int 13 let trailer: String 14 @Binding var isFinished: Bool? 15 16 @State private var startDate = Date() 17 18 init(_ title: String, seconds: Int,_ trailer: String? = nil, isFinished: Binding<Bool?> = .constant(nil)) { 19 self.title = title 20 self.seconds = seconds 21 self.trailer = trailer ?? String(localized: "seconds") 22 self._isFinished = isFinished 23 } 24 25 func remainingTime(_ elapsed: Int) -> Int { 26 let remaining = seconds - elapsed 27 if remaining <= 0 { 28 if isFinished != nil { 29 DispatchQueue.main.async { 30 withAnimation { 31 isFinished = true 32 } 33 // print("❗️remainingTime.DispatchQueue: \(remaining)") 34 DispatchQueue.main.asyncAfter(deadline: .now() + 1.2) { 35 withAnimation { 36 isFinished = nil 37 } 38 // print("❗️remainingTime.DispatchQueue isFinished") 39 } 40 } 41 } 42 return 0 43 } 44 return remaining 45 } 46 47 var body: some View { 48 // let _ = print("❗️startDate: \(startDate), isFinished: \(isFinished)") 49 HStack { 50 Text(title) 51 TimelineView(.animation) { context in 52 let elapsed = Int(context.date.timeIntervalSince(startDate)) 53 let remaining = remainingTime(elapsed) 54 // if remaining > 290 { 55 // let _ = print("❗️remainingTime: \(remaining), isFinished: \(isFinished)") 56 // } 57 let isFinished = remaining <= 0 58 let text = Text(verbatim: "\(isFinished ? 0 : remaining)") 59 if isFinished { 60 text 61 } else if #available(iOS 17.0, *) { 62 text 63 .contentTransition(.numericText(countsDown: true)) 64 .animation(.default, value: elapsed) 65 } else if #available(iOS 16.4, *) { 66 text 67 .animation(.default, value: elapsed) 68 } else { 69 text 70 } 71 }.monospacedDigit() 72 Text(trailer) 73 }.accessibilityElement(children: .combine) 74 } 75 }