我正在使用Swift UI创建一个倒数计时器应用程序。我试图在其中添加圆形进度条,但外观始终不变。
我准备了2个文件。其中一个编码为倒计时过程,另一个文件编码为UI。我使数据与键@ObservableObject,过程代码的@Public和UI代码的@ObservedObject链接。
设置为“计数器”作为变量的数字开始每秒倒数1。我通过在Xcode控制台中打印数字来确认它可以工作。
数字向下,但进度条不会更改,最后,一旦计数为0,进度条就会消失。
程序代码
import SwiftUI
class CountDownTimer: ObservableObject {
@Published var counter: CGFloat = 10
let interval = 1.0
var timer: Timer?
func start() {
timer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true, block: { _ in
self.counter -= 1
print(self.counter)
if self.counter <= 0 {
self.timer?.invalidate()
self.timer = nil
}
})
}
func stop() {
self.timer?.invalidate()
}
}
UI代码
struct PresentationView: View {
@ObservedObject var countDownTimer = CountDownTimer()
var body: some View {
NavigationView {
VStack {
Spacer()
VStack {
ZStack {
Text(String(format: "%.0f", countDownTimer.counter))
.font(Font.largeTitle.monospacedDigit())
.fontWeight(.light)
.padding()
Circle()
.stroke(Color(.systemIndigo), style: StrokeStyle(lineWidth: 20, lineCap: .round, lineJoin: .bevel))
.aspectRatio(contentMode: .fit)
.padding()
Circle().trim(from: 0, to: countDownTimer.counter)
.stroke(Color(.systemTeal), style: StrokeStyle(lineWidth: 20, lineCap: .round, lineJoin: .bevel))
.aspectRatio(contentMode: .fit)
.rotationEffect(Angle(degrees: -90))
.padding()
}
Spacer()
// スタートボタンとストップボタン
HStack {
Button(action: {self.countDownTimer.stop()}) {
Text("STOP")
.fontWeight(.light)
.foregroundColor(.white)
}.frame(maxWidth: 75, maxHeight: 75)
.padding()
.background(Color(.systemIndigo))
.cornerRadius(100)
.padding()
Button(action: {self.countDownTimer.start()}) {
Text("START")
.fontWeight(.light)
.foregroundColor(.white)
}.frame(maxWidth: 75, maxHeight: 75)
.padding()
.background(Color(.systemTeal))
.cornerRadius(100)
.padding()
}
}
}
}
}
}
如果您知道如何解决此问题,请帮助我。我的英语可能会因为我的第二语言而无法使用。
谢谢。
您可能需要分endFraction
由10,
Circle().trim(from: 0, to: countDownTimer.counter / 10) // Dividing by 10
.stroke(Color(.systemTeal), style: StrokeStyle(lineWidth: 20, lineCap: .round, lineJoin: .bevel))
.aspectRatio(contentMode: .fit)
.rotationEffect(Angle(degrees: -90))
.padding()
谢谢!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句