[ad_1]
The Charts framework is considered one of my favorite options for the brand new model of SwiftUI in iOS 16. Previous to iOS 16, you could construct your individual charts or depend on third social gathering library to render charts for you. With the discharge of this new framework, Apple has made it very simple for builders to create animated and interactive charts.
I’ve briefly mentioned the utilization of the Charts API in this put up. For this tutorial, let’s see the way to use the APIs to create a line chart.
The Climate Information
To display the SwiftUI Charts API, we’ll create a line chart that shows the typical temperature of Hong Kong, Taipei, and London from 2021-Jul to 2022-Jun.
To retailer the climate information, I created a WeatherData struct like under:
  init(yr: Int, month: Int, day: Int, temperature: Double) {
    self.date = Calendar.present.date(from: .init(yr: yr, month: month, day: day)) ?? Date()
    self.temperature = temperature
  }
}
|
struct WeatherData: Identifiable {   let id = UUID()   let date: Date   let temperature: Double    init(yr: Int, month: Int, day: Int, temperature: Double) {     self.date = Calendar.present.date(from: .init(yr: yr, month: month, day: day)) ?? Date()     self.temperature = temperature   } } |
The Chart initializer takes in an inventory of Identifiable objects. Because of this we make the WeatherData conform the Identifiable protocol.
For every metropolis, we create an array to retailer the climate information. Right here is an instance for London:
|
let londonWeatherData = [ WeatherData(year: 2021, month: 7, day: 1, temperature: 19.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2021, month: 8, day: 1, temperature: 17.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2021, month: 9, day: 1, temperature: 17.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2021, month: 10, day: 1, temperature: 13.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2021, month: 11, day: 1, temperature: 8.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2021, month: 12, day: 1, temperature: 8.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2022, month: 1, day: 1, temperature: 5.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2022, month: 2, day: 1, temperature: 8.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2022, month: 3, day: 1, temperature: 9.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2022, month: 4, day: 1, temperature: 11.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2022, month: 5, day: 1, temperature: 15.0), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â WeatherData(year: 2022, month: 6, day: 1, temperature: 18.0) ] |
To retailer the climate information of the cities, we even have an array for that:
|
let chartData = [ (city: “Hong Kong”, data: hkWeatherData), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â (city: “London”, data: londonWeatherData), Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â (city: “Taipei”, data: taipeiWeatherData) ] |
Making a Easy Line Chart Utilizing Chart and LineMark
To create any sorts of chart utilizing the Charts framework, you need to first import the Chartsframework:
Subsequent, you begin with the Chart view. Contained in the Chart view, you present a set of LineMark to create a line chart. Right here is an instance:
|
struct SimpleLineChartView: View {     var physique: some View {         VStack {             Chart {                 ForEach(hkWeatherData) { merchandise in                     LineMark(                         x: .worth(“Month”, merchandise.date),                         y: .worth(“Temp”, merchandise.temperature)                     )                 }             }             .body(top: 300)         }     } } |
What the code above does is to plot a line chart for displaying the typical temperature of Hong Kong. The ForEach assertion loops via all objects saved in hkWeatherData. For every merchandise, we create a LineMark object that the x axis is about to the date and the y axis is about to the typical temperature.
Optionally, you possibly can resize the chart utilizing the body modifier. Should you preview the code in Xcode preview, it is best to see the next line chart:

Customizing Chart Axes
You may customise each x and y axes through the use of the chartXAxis and chartYAxis modifiers respectively. Let’s say, if we wish to show the month labels utilizing the digit format, we are able to connect the chartXAxis modifier to the Chart view like this:
|
.chartXAxis {     AxisMarks(values: .stride(by: .month)) { worth in         AxisGridLine()         AxisValueLabel(format: .dateTime.month(.defaultDigits))        } } |
Inside chartXAxis , we create a visible mark referred to as AxisMarks for the values of month. For every worth, we show a worth label through the use of a particular format. This line of code tells SwiftUI chart to make use of the digit format:
|
.dateTime.month(.defaultDigits) |
On prime of that, we added some grid strains through the use of AxisGridLine.
For the y-axis, as a substitute of show the axis on the trailing (or proper) facet, we wish to swap it to the main (or left) facet. To try this, connect the chartYAxis modifier like this:
|
.chartYAxis { Â Â Â Â AxisMarks(place: .main) } |
Should you’ve made the change, Xcode preview ought to replace the chart like under. The y-axis is moved to the left facet and the format of month is modified. Plus, it is best to see some grid strains.

Customizing the Background Colour of the Plot Space
The chartPlotStyle modifier lets you change the background colour of the plot space. Connect the modifier to the Chart view like this:
|
.chartPlotStyle { plotArea in     plotArea         .background(.blue.opacity(0.1)) } |
We will then change the plot space utilizing the background modifier. For instance, we modify the plot space to gentle blue.

Making a Multi-line Chart
Now the chart shows a single supply of information (i.e. the climate information of Hong Kong), so how can we show the climate information of London and Taipei in the identical line chart?
You may rewrite the code of Chart view like this:
|
Chart {     ForEach(chartData, id: .metropolis) { sequence in         ForEach(sequence.information) { merchandise in             LineMark(                 x: .worth(“Month”, merchandise.date),                 y: .worth(“Temp”, merchandise.temperature)             )         }         .foregroundStyle(by: .worth(“Metropolis”, sequence.metropolis))     } } |
We’ve got one other ForEach to loop via all of the cities of the chart information. Right here, the foregroundStyle modifier is used to use a unique colour for every line. You don’t need to specify the colour. SwiftUI will mechanically decide the colour for you.

Proper now, all of the cities share the identical image. If you wish to use a definite image, place the next line of code after foregroundStyle:
|
.image(by: .worth(“Metropolis”, sequence.metropolis)) |
Now every metropolis has its personal image within the line chart.

Customizing the Interpolation Technique
You may alter the interpolation technique of the road chart by attaching the interpolationMethod modifier to LineMark. Right here is an instance:
|
.interpolationMethod(.stepStart) |
Should you change the interpolation technique to .stepStart, the road chart now appears to be like like this:

Apart from .stepStart, you possibly can check out the next choices:
- cardinal
- catmullRom
- linear
- monotone
- stepCenter
- stepEnd
Abstract
The Charts framework is a superb addition to SwiftUI. Even in case you simply start studying SwiftUI, you possibly can create pleasant charts with just a few strains of code. Whereas this tutorial focuses on line charts, the Charts API makes it very simple for builders to transform the chart to different varieties reminiscent of bar chart. You may take a look at the Swift Charts documentation for additional studying.
Observe: We’re updating our Mastering SwiftUI e-book for iOS 16. If you wish to begin studying SwiftUI, take a look at the e-book right here. You’ll obtain a free replace later this yr.
[ad_2]
