ios - 如何在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)
}
}
}
您还可以将计时器逻辑移动到视图模型,例如:
推荐阅读
- sql - 数据对比查询,如何优化?
- node.js - 如果 Firestore 在指定路径的更新失败,firebase 会向我们收取写入或读取费用吗?
- javascript - 获取数据并推送到数组
- pdf - 由inkscape创建的PDF包含通过虚线的细灰线
- python - 如何简化具有两个不等式的表达式:如果 x <= y 和 x >= n
- python - 数据框和循环
- javascript - 引导模式淡出窗口但不弹出
- python - 如何在 Python Selenium 中按类名查找元素?
- azure - Azure 数据资源管理器 - 日志查询
- java - 如何在 androidTest(仪表测试)测试类中从我的应用程序访问资源?