1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
| import SwiftUI
struct TimerView: View { @State var count1: Int = 0 @State var count2: Int = 0 @State var count3: Int = 0 @State var timer1: Timer? let timer2 = Timer.publish(every: 1.0, on: .main, in: .common).autoconnect() var body: some View { VStack (spacing: 55) { Button(action: {setupTimer()}) { Text("start") } Button(action: {resetTimer()}) { Text("reset") } } .onAppear { Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true){ (_) in count3 += 1 print("----> timer3 running \(count3)") } } .onReceive(timer2) { input in count2 += 1 print("----> timer2 running \(count2)") } } private func setupTimer() { guard timer1 == nil else { return } timer1 = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { _ in count1 += 1 print("----> timer1 running \(count1)") }) } private func resetTimer() { timer1?.invalidate() timer1 = nil } }
|