如何为“Timer.publish()”声明变量

Tio*_*Tio 5 swift5 swiftui

我目前正在使用 SwiftUI 开发一个应用程序。

我正在尝试制作一个计时器应用程序,并且想控制 Timer.publish() 方法,因此我制作了启动和停止计时器的方法。

但我不知道如何声明变量Timer.publish(),然后代码不起作用......

我如何声明变量Timer.publish()


ContentView.swift(*此代码无法构建)

import SwiftUI

struct ContentView: View {
    
    @State var timer:Timer! //I don't know how to declare here...
    @State var counter = 0
    
    var body: some View {
        VStack{
            HStack{
                Text("RUN")
                    .onTapGesture {
                        startTimer()
                        
                    }
                Text("STOP")
                    .onTapGesture {
                        stopTimer()
                    }
            }
            
            Text(String(counter))
                .padding()
        }
        
        .onReceive(timer) { _ in
            print("onRecieve")
            counter += 1
            
        }
    }
    
    func stopTimer() {
        self.timer.upstream.connect().cancel()
    }
    
    func startTimer() {
        self.timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
    }
}
Run Code Online (Sandbox Code Playgroud)

TimerControlApp.swift

import SwiftUI

@main
struct TimerControlApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Xcode:版本 12.0.1

iOS:14.0

生命周期:SwiftUI 应用程序

Mof*_*waw 7

为了控制开始,你的计时器应该是类型Timer.TimerPublisher。这样您就可以手动启动计时器.connect()

@State var timer: Timer.TimerPublisher = Timer.publish(every: 1, on: .main, in: .common)
Run Code Online (Sandbox Code Playgroud)
func startTimer() {
    timer = Timer.publish(every: 1, on: .main, in: .common)
    _ = timer.connect()
}
Run Code Online (Sandbox Code Playgroud)
func stopTimer() {
    timer.connect().cancel()
}
Run Code Online (Sandbox Code Playgroud)