具有不同宽度的SwiftUI视图,根据百分比填充
创建视图的最佳方法是什么(如下图所示)?所以它的宽度是文本内容和填充的大小,考虑到百分比。我尝试了几个选项,通过 Frame 和 GeometryReader,但结果要么是固定宽度的视图,要么是屏幕宽度的视图。
也许有更优雅的方式。
回答
var percent: CGFloat = 0.7
var body: some View {
VStack(alignment: .leading) {
cell("Lorem")
cell("Lorem ipsum")
cell("Lorem ipsum dolor")
cell("Lorem ipsum dolor sit")
cell("Lorem ipsum dolor sit amet")
}
}
@ViewBuilder
func cell(_ string: String) -> some View {
Text(string)
.padding(.all, 5)
.background(
GeometryReader { geometry in
ZStack(alignment: .leading) {
Rectangle()
.foregroundColor(.green)
.frame(width: geometry.size.width * percent, height: geometry.size.height)
Capsule()
.stroke(Color.black, lineWidth: 1)
}
}
)
.clipShape(Capsule())
}