我想在 SwiftUI 中創建這樣的 UI。我嘗試使用 path 和 geometryReader 但我找不到合適的解決方案。

uj5u.com熱心網友回復:
也許是這樣的?
struct ProbabilityView: View {
var title: String
var value: Double
var body: some View {
VStack(alignment: .leading) {
Text(title)
GeometryReader { proxy in
ZStack(alignment: .leading) {
HStack(spacing: 0) {
Color.green
Color.yellow
Color.red
}
.cornerRadius(8)
.frame(maxHeight: 16)
Text(formatted)
.font(.callout)
.padding(.vertical, 3)
.frame(width: 52)
.background(Color(.systemBackground))
.cornerRadius(16)
.shadow(radius: 8)
// Substract the width of the bubble
.offset(x: (proxy.size.width - 52) * value)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
.animation(.default, value: value)
}
.padding(.bottom, 10)
}
var formatted: String {
let value = self.value * 100
return "\(Int(value.rounded())) %"
}
}
演示
struct ContentView: View {
@State private var value = 0.0
var body: some View {
List {
Section {
ProbabilityView(title: "Virus probability score", value: value)
}
Section {
Button {
value = 0
} label: {
Text("0%")
}
Button {
value = 0.5
} label: {
Text("50%")
}
Button {
value = 1.0
} label: {
Text("100%")
}
Button {
value = Double.random(in: 0...1)
} label: {
Text("Random")
}
}
}
.listStyle(.grouped)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/506290.html
