我想看看是否可以更改单元格的背景颜色,但要根据百分比填充它
我正在列表中创建单元格{}
let gradient = LinearGradient(colors: [.green, .white], startPoint: .leading, endPoint: .trailing)
List {
Section(header: Text("Total")) {
Text("Total Obtained: \(totalObtained) - \(totalComplete)%")
.listRowBackground(gradient)
}
}
totalComplete 有百分比变量
我在问你想要填充的样子,当你回复时可能会改变我的答案😄
与此同时,如果您只是使用渐变来粗略地说明部分填充的外观,那么这里将尝试展示如何实现它。它使用
GeometryReader
来传递单元格的宽度,并将背景设置为该宽度的一小部分。调整滑块以查看它是否有效。
struct ContentView: View {
private let targetObtained = 123456.0
@State private var totalComplete = 50.0
private var totalObtained: Double {
targetObtained * totalComplete / 100.0
}
var body: some View {
VStack {
List {
Section(header: Text("Total")) {
Text("Total Obtained: \(totalObtained) - \(totalComplete)%")
.listRowBackground(
GeometryReader { proxy in
Color.green
.frame(width: (totalComplete / 100.0) * proxy.size.width)
}
)
}
}
.frame(height: 150)
Slider(
value: $totalComplete,
in: 0...100
)
.padding()
}
}
}
我猜你想要这样的东西:
您可以通过使用不同的初始化程序来设置渐变来做到这一点。
像这样设置具有四个停止点的梯度,其中
f
是完整的分数,从 0 到 1:
四站如下:
停止索引 | 地点 | 颜色 |
---|---|---|
0 | 0 |
|
1 |
|
|
2 |
|
|
3 | 1 |
|
注意停靠点 1 和 2 位于同一位置,因此该位置的颜色变化是瞬时的,不会显示可见的渐变。
这是我动画中行视图的代码:
struct RowView: View {
@State var progress: CGFloat = 0
@State var running = false
private func myGradient() -> some View {
LinearGradient(
stops: [
.init(color: .green, location: 0),
.init(color: .green, location: progress),
.init(color: .white, location: progress),
.init(color: .white, location: 1),
],
startPoint: .leading,
endPoint: .trailing
)
}
var body: some View {
HStack {
Text("\(running ? "Running" : "Stopped"): \(progress, format: .percent)")
Spacer()
}
.listRowBackground(myGradient())
.contentShape(Rectangle())
.onTapGesture {
running.toggle()
}
.task {
while !Task.isCancelled {
if running && progress < 1 {
progress = min(progress + 0.1, 1)
}
try? await Task.sleep(for: .seconds(1.0 / 6))
}
}
}
}