article

Thursday, September 9, 2021

SwiftUI how to create Custom Bar Chart

SwiftUI how to create Custom Bar Chart

ContentView.swift
 
//
//  ContentView.swift
//  swiftuidev
//
//  Created by Cairocoders
//

import SwiftUI

struct ContentView: View {
    
    @State var bar1 : CGFloat = 0
    
    var body: some View {
        
        GeometryReader {geo in
            VStack {
            
                HStack {
                    
                    Button(action:  {
                        self.bar1 = geo.size.width / 2 - 20
                    }) {
                        Text("Day 1").padding(15)
                    }
                    .background(Color.orange)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                    
                    Button(action:  {
                        self.bar1 = geo.size.width * 0.25 - 20
                    }) {
                        Text("Day 2").padding(15)
                    }
                    .background(Color.blue)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                    
                    Button(action:  {
                        self.bar1 = geo.size.width * 0.25 - 90
                    }) {
                        Text("Day 3").padding(15)
                    }
                    .background(Color.red)
                    .foregroundColor(.white)
                    .cornerRadius(8)
                }
                
                Bar(percent: self.bar1, color: .green)
                
            }// End VStack
            .onAppear {
                self.bar1 = geo.size.width / 2 - 20
            }.animation(.spring())
        }
    }
}

struct Bar : View {
    
    var percent : CGFloat = 0
    var color : Color = .white
    
    var body: some View {
        
        HStack {
            Capsule().fill(color).frame(width: percent, height: 30)
            
            Spacer()
        }.padding(10)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Related Post