[英]Circular Progress Bar with Swift UI
我正在使用 Swift UI 創建倒數計時器應用程序。 我試圖在其中添加一個圓形進度條,但它的外觀從未改變。
我准備了2個文件。 其中一個是關於倒計時程序的編碼,另一個文件是關於 UI 的編碼。 我使用鍵@ObservableObject、@Public 為過程代碼和@ObservedObject 為UI 代碼建立數據鏈接。
將“計數器”設置為變量的數字開始每秒倒數 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()
}
}
用戶界面代碼
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()
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.