首页 > 解决方案 > 如何在swiftUI中每秒自动随机化一个数字

问题描述

我正在尝试创建一个计数器,以便每秒随机化一个数字。

到目前为止,我得到了这个代码,但它会自动激活。很高兴知道如何使用按钮激活此计时器。

我的代码:

struct BSR: View {
    @State private var NumBSR = "---"

    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()

    var body: some View {
        ZStack {
            Image("BSR")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 62, height: 61, alignment: .center)

            Text(String(NumBSR))
                .font(.body)
                .foregroundColor(.white)
                .frame(width: 50, height: 40, alignment: .bottom)

        }.onReceive(timer, perform: { time in
            let Num = Int.random(in: 0...5)
            NumBSR = String(Num)
        })
    }
}

对不起,如果我不能写代码属性,我还在学习。谢谢你的帮助。

标签: iosswifttimerswiftui

解决方案


您可以尝试以下方法:

struct BSR: View {
    @State private var NumBSR = "---"
    @State private var timer: AnyCancellable? // declare as `@State`, assign later

    var body: some View {
        ZStack {
            Image("BSR")
                .resizable()
                .aspectRatio(contentMode: .fit)
                .frame(width: 62, height: 61, alignment: .center)
            VStack {
                Text(String(NumBSR))
                    .font(.body)
                    .foregroundColor(.white)
                    .frame(width: 50, height: 40, alignment: .bottom)
                Button(action: startTimer) { // create timer on button tap
                    Text("Start timer")
                }
            }
        }
    }

    func startTimer() {
        // create on demand, not when the the view is initialised
        timer = Timer.publish(every: 1.0, on: .main, in: .common)
            .autoconnect()
            .sink { _ in
                let Num = Int.random(in: 0...5)
                NumBSR = String(Num)
            }
    }
}

您还可以将计时器逻辑移动到视图模型,例如:


推荐阅读