Bar Color View – SwiftUI

4 0

In this code example we create a bar with color and its ratio in Swift and SwiftUI. It is very cool, when you have values and want to show that ratio in colors.

import SwiftUI

struct BarColorView: View {
    
    var colors: [Color]
    var values: [CGFloat]
    
    let screenWidth = UIScreen.main.bounds.size.width
    
    var body: some View {
        let sum = values.reduce(0, +)
        ZStack {
            HStack(spacing: 0) {
                ForEach(Array(zip(colors, values)), id: \.0) { item in
                    
                    Rectangle()
                        .foregroundColor(item.0)
                        .frame(maxWidth: item.1/sum * screenWidth)
                }
            }
            .cornerRadius(10)
            .frame(maxWidth: screenWidth, maxHeight: 25, alignment: .leading)
        }
    }
}

struct BarColorView_Previews: PreviewProvider {
    static var previews: some View {
        BarColorView(colors: [Color.red, Color.blue, Color.green, Color.pink], values: [10.0, 100.0, 30.0, 80])
            .previewLayout(PreviewLayout.sizeThatFits)
            .padding()
            .previewDisplayName("BarColorView")
    }
}

The Code is very simple and the output you see down here:

In this code example we create a bar with color and its ratio in Swift and SwiftUI.
BarColorView Output from the Code above
Happy
Happy
40 %
Sad
Sad
0 %
Excited
Excited
60 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %