我目前正在使用 SwiftUI 开发一个应用程序。
我正在尝试使用计时器类制作进度条。
当我在for a of的参数0.05中设置一个小值时,我会收到以下警告:everyTimer.publish()widthRectangle
框架尺寸无效(负或非有限)。
我该如何解决这个问题?
以下是代码:
时间管理器.swift
import SwiftUI
class TimeManager: ObservableObject {
var timer = Timer.publish(every: 0.05, on: .main, in: .common).autoconnect()
}
Run Code Online (Sandbox Code Playgroud)
ProgressBar.swift
import SwiftUI
struct ProgressBar: View {
@EnvironmentObject var timeManager:TimeManager
@Binding var duration:Double
@Binding var maxValue:Double
var body: some View {
VStack(alignment:.leading){
RoundedRectangle(cornerRadius: 30)
.fill(Color.red)
.frame(width:CGFloat(self.duration / self.maxValue) * 150, height: 12)
Text("value:\(CGFloat(self.duration / self.maxValue) )")
}
.onReceive( self.timeManager.timer) { _ in
if self.duration > 0 {
self.duration -= 0.05
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
内容视图.swift
import SwiftUI
struct ContentView : View {
@State var duration:Double = 8
@State var maxValue:Double = 8
var body: some View {
ProgressBar(duration: $duration, maxValue: $maxValue)
}
}
Run Code Online (Sandbox Code Playgroud)
Xcode:版本 12.0.1
iOS:14.0
这部分可能会导致负数duration(例如,当durationis时0.0001):
if self.duration > 0 {
self.duration -= 0.05
}
Run Code Online (Sandbox Code Playgroud)
因为duration后来用于:
.frame(width: CGFloat(self.duration / self.maxValue) * 150, height: 12)
Run Code Online (Sandbox Code Playgroud)
你会得到一个负的宽度参数。
解决方案是确保duration永远不会低于 0。
就像是:
if self.duration > 0.05 {
self.duration -= 0.05
} else {
self.duration = 0
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2079 次 |
| 最近记录: |