Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI view with different widths with fill depending on the percentage

what is the best way to create a view (as in the image below)? so that its width is the size of the text content and the fill, taking into account the percentage. I tried several options, through Frame and GeometryReader, but it turns out either a view with a fixed width or for the width of the screen.

Maybe there is a more elegant way.

enter image description here

like image 571
Aleksei Avatar asked Nov 19 '25 01:11

Aleksei


1 Answers

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())
}

enter image description here

like image 127
Philip Dukhov Avatar answered Nov 20 '25 16:11

Philip Dukhov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!