Better Programming

Advice for programmers.

Follow publication

SwiftUI Bar Charts

Anupam Chugh
Better Programming
Published in
3 min readNov 4, 2019

What we’ll achieve

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:

Disclaimer: The above stats do not exactly represent my Medium stats.

Implementation

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

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:

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:

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.

Responses (4)

Write a response