Categories
iOS SwiftUI

SwiftUI Bar Charts

SwiftUI is the talk of the town. The declarative UI pattern is here to stay and building cool and awesome UIs is easier than ever before.

Previously, we implemented SwiftUI with Alerts, Pickers, and Gradients. Now, it’s time for some custom views!

The goal of this article is to build bar charts with SwiftUI. For this, we’ll be using SwiftUI shapes and gradients. Also, we’ll be binding the different bar chart shapes to a segmented picker view.

Sneak Peek

Before we deep dive into the SwiftUI implementation, here’s a sneak peek at what we’ll be building:

Implementation

For starters, you need to create a new Xcode project in SwiftUI. Add the following piece of code in your ContentView:

import SwiftUI

struct ContentView: View {

    @State var pickerSelection = 0
    @State var barValues : [[CGFloat]] =
        [
        [5,150,50,100,200,110,30,170,50],
        [200,110,30,170,50, 100,100,100,200],
        [10,20,50,100,120,90,180,200,40]
        ]
    var body: some View {
        ZStack{
            Color(.black).edgesIgnoringSafeArea(.all)

            VStack{
                Text("Bar Charts").foregroundColor(.white)
                    .font(.largeTitle)

                Picker(selection: $pickerSelection, label: Text("Stats"))
                    {
                    Text("Views").tag(0)
                    Text("Reads").tag(1)
                    Text("Fans").tag(2)
                }.pickerStyle(SegmentedPickerStyle())
                    .padding(.horizontal, 10)

                HStack(alignment: .center, spacing: 10)
                {
                    ForEach(barValues[pickerSelection], id: \.self){
                        data in
                        
                        BarView(value: data, cornerRadius: CGFloat(integerLiteral: 10*self.pickerSelection))
                    }
                }.padding(.top, 24).animation(.default)
            }
        }
    }


    init() {
        UISegmentedControl.appearance().selectedSegmentTintColor = .darkGray
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .selected)
        UISegmentedControl.appearance().setTitleTextAttributes([.foregroundColor: UIColor.white], for: .normal)
    }
}

In the above code, we’ve built a ZStack to add views on top of each other. Inside that, we’ve set a vertical stack for the Text, Picker, and a Horizontal Stack.

The two states, pickerSelection and barValues, are correlated. Based on the pickerSelection value, the respective bar chart values and shapes are tweaked slightly (notice how the cornerRadius of the bar chart changes).

The bar chart uses a horizontal stack to display each of the single bar views as we shall see next.

To change the segmented picker control styles in SwiftUI, we need to do the necessary UIKit additions in the init method.

Building Bar Views

To build our custom bar views, we need to use SwiftUI’s Shape API. It supports a variety of shapes, such as Circle, Capsule, Rounded Rectangle, etc.

The code for building the bar views is given below:

struct BarView: View{

    var value: CGFloat
    var cornerRadius: CGFloat
    
    var body: some View {
        VStack {

            ZStack (alignment: .bottom) {
                RoundedRectangle(cornerRadius: cornerRadius)
                    .frame(width: 30, height: 200).foregroundColor(.black)
                RoundedRectangle(cornerRadius: cornerRadius)
                    .frame(width: 30, height: value).foregroundColor(.green)
                
            }.padding(.bottom, 8)
        }
        
    }
}

Here, we’ve used two RoundedRectangles aligned to the bottom (you can use the shapeCapsule as well). One acts as the container and has a fixed height and the other has a dynamic height based on the value it holds.

Fill Custom Views With Gradients

We can further beautify our bar charts by adding gradients as the fill color. The following code adds a LinearGradient to the BarView:

RoundedRectangle(cornerRadius: cornerRadius).fill(LinearGradient(gradient: Gradient(colors: [.purple, .red, .blue]), startPoint: .top, endPoint: .bottom))
.frame(width: 30, height: value)

In return, we get a new look for the bar charts in our SwiftUI preview, as shown below:

swiftui-bar-charts

 

The full source code of Bar Charts Using SwiftUI is available in this GitHub Repository.

What’s Next

Building bar charts with SwiftUI was quick and easy. Moving forward, we’ll explore the other cool charts: pie charts, donut charts, and line charts in SwiftUI.

That wraps up this short piece. I hope you enjoyed reading it.

By Anupam Chugh

iOS Developer exploring the depths of ML and AR on Mobile.
Loves writing about thoughts, technology, and code.

Leave a Reply

Your email address will not be published. Required fields are marked *