如何在swiftUI中每秒自动随机化一个数字
How to randomize a number automatically every each second in 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)
})
}
}
对不起,如果我不会写代码属性,我还在学习中。
感谢您的帮助。
您可以尝试以下方法:
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)
}
}
}
您还可以将计时器逻辑移动到视图模型中,例如:
我正在尝试创建一个计数器,以便每秒随机生成一个数字。
到目前为止,我收到了这段代码,但它会自动激活。很高兴知道如何使用按钮激活此计时器。
我的代码:
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)
})
}
}
对不起,如果我不会写代码属性,我还在学习中。 感谢您的帮助。
您可以尝试以下方法:
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)
}
}
}
您还可以将计时器逻辑移动到视图模型中,例如: