我正在尝试创建一个自定义百分比条形图,如下图所示
但是,我无法以编程方式设置条宽度,我在做什么错了?
设置.frame(width:UIScreen.main.bounds.width * percent,height:23)会产生以下错误:对成员'frame(width:height:alignment :)'的引用不明确
import SwiftUI
struct BarChartView : View {
@Binding var percent: Float
init(percentage: Binding<Float>){
self._percent = percentage
}
var body: some View {
ZStack {
Rectangle().fill(Color.yellow).frame(height: 30).border(Color.black, width:1)
HStack {
RoundedRectangle(cornerRadius: 5)
.fill(Color.green).frame(width: 300, height:23).padding(2)
Spacer()
}
HStack {
Text("Bar Chart View").padding (2)
Spacer()
Text("\(String(format: "%02.f", arguments: [self.percent]))%")
}
}
}
}
有没有一种方法可以确定ZStack中第一个矩形的宽度并计算出该百分比。我希望这也可以在横向模式下自动更新。
答案 0 :(得分:2)
您可以使用GeometryReader来处理尺寸,但是在这种情况下,我认为使用形状更合适:
import SwiftUI
struct BarChartView : View {
@Binding var percent: Float
init(percentage: Binding<Float>){
self._percent = percentage
}
var body: some View {
HStack {
Text("Bar Chart View").padding (5)
Spacer()
Text("\(String(format: "%02.f", arguments: [self.percent * 100]))%").padding(5)
}
.background(LeftPart(pct: CGFloat(percent)).fill(Color.green))
.background(RightPart(pct: CGFloat(percent)).fill(Color.yellow))
.padding(10)
}
struct LeftPart: Shape {
let pct: CGFloat
func path(in rect: CGRect) -> Path {
var p = Path()
p.addRoundedRect(in: CGRect(x: 0, y: 0, width: rect.size.width * pct, height: rect.size.height), cornerSize: .zero)
return p
}
}
struct RightPart: Shape {
let pct: CGFloat
func path(in rect: CGRect) -> Path {
var p = Path()
p.addRoundedRect(in: CGRect(x: rect.size.width * pct, y: 0, width: rect.size.width * (1-pct), height: rect.size.height), cornerSize: .zero)
return p
}
}
}
struct ContentView: View {
var body: some View {
BarChartView(percentage: .constant(0.75))
}
}