J. Edgell
J. Edgell

Reputation: 1865

In SwiftUI, how do I create a dynamic rectangle for a bar chart?

I'm trying to create a custom percentage bar chart like the one below

enter image description here

however, I'm unable to set the bar width programmatically, what am I doing wrong?

Setting .frame(width: UIScreen.main.bounds.width * percent, height:23) produces the following error : Ambiguous reference to member '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]))%")
                }

            }
        }

}

Is there a way to determine the width of the first rectangle in the ZStack and calc a percentage off of that. I would like this to automatically update in landscape mode too, if possible.

Upvotes: 0

Views: 2088

Answers (1)

kontiki
kontiki

Reputation: 40539

You could use GeometryReader to play with dimensions, but in this case I think using a shape is a much better fit:

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

Upvotes: 2

Related Questions