具有不同宽度的 SwiftUI 视图,根据百分比进行填充

SwiftUI view with different widths with fill depending on the percentage

创建视图的最佳方式是什么(如下图所示)?这样它的宽度就是文本内容和填充的大小,同时考虑到百分比。我尝试了几个选项,通过 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())
}