Creating a Line Chart in Swift 3 and iOS 10

Note: Although Swift 4 is out and I have promised that I will get an updated version out, I am currently got a lot of work on at the moment I — This should work with Swift 4 but I test it within the next week or so once I get a chance to test and update this. Hope you understand if there is a error why it hasn’t been updated 😊

If you ever work with Data and smart-phones, you are one day going to have to create a chart. In iOS there is an amazing library called Charts by Daniel Cohen Gindi which is based off MPAndroidChart.

This library contains 8 different types of charts and is hugely customisable and fully works in Object-C and swift.

Our end goal

Sadly though, the iOS demo that is given to us is in Object-C. This is annoying for many new developers like me out there, who started coding since Swift has been introduced and have never touched Object-C.

I am currently working on an app at the moment that takes in user input and displays it to the user as a Line Chart. I tried the demo only to find it in Object C.

Great.

While I am thankful for the Demo’s being included, I decided instead googling for other examples in Swift 3 to no luck. There are other demo’s and guides there but they were either in a prior version of swift which didn’t want to compile, or was missing too much information.

After reading the API, the macOS tutorial I got it working. So, if you are like me and are struggling, here’s my guide to help you out!

So, let’s get started. I’m going to start from the beginning (from installing Cocopods) so just scroll to the part you want :)

For this I am going to use Xcode 8.3.3 and develop for iOS — you can download this from the app store and the same code can be applied to macOS.

All my code will be on GitHub which is on the bottom of this pageInstalling Cocopods and starting our project

We are first going you want to install Cocopods. This is how we are going to install iOS charts. To do this we first need Cocopods which you can find the instructions here.

Once that is done, we can start a new project to do this we need to open Xcode and select “Create a new Xcode Project”

From that we click a Single View application for iOS :

From there I am going to create a new project in Swift called LineChartExample. Make sure swift is selected as language.

You need an Organisation Name — I am just called mine HelloWorld.

Save it in documents and somewhere you can navigate to quickly.

Now exit Xcode. Open terminal application and go to the saved location of your file. (you can drag finder files in Xcode)

For me I had to type in:

cd /Users/osiansmith/projects/Xcode/LineChartExample

From there we want to type in:

pod init

Give it a moment or two… or three and boom a Podfile appears — navigate in finder to your project file and open Podfile

Open it in your favourite text edior such as Atom and paste in:

pod 'Charts'

Save the file and exit. Then lets go back to the terminal and type:

pod install

If you have any errors (I didn’t) try:

pod repo update

And we now want to go back to finder and open

LineChartExample.xcworkspace

This is the file we are going to use from now onwards

Go to Main.Storyboard, we are going to be making a simple GUI here

Go down to the object library and add a view — this is what the graph is going to fit in.

We are going to add this to the View Controller. You also want to add a text field and a button. This is how mine looks:

Now we are just going to set constraints on the view controller. Select everything on the view controller and go down “Resolve Auto Layout issues” and select “Reset to suggested constraints.” This means that our app will look very similar on an iPhone SE (4 inch screen) and iPad Pro (12 in screen).

There we go — that’s all our GUI done. My View is pink just to make it more visible to you.

One last thing to do! Select the view and go to “Show Identity inspector.”

Under Custom Class, select LineChartView. it now should look like:

There we go! There is our award-winning GUI.

Linking up everything

We now need to just link up everything on the Storyboard to the View Controller.

In iOS you have a custom class for each view — think of the Storyboard as the front end — the thing that is shiny — and the View Controller as the back end.

To link them up, Click the Assistant Editor on the top right corner:

And click on the text field and drag it to the ViewController near the top such as this:

You should then get this pop up. Call it txtTextBox

Do the same for the View and call it chtChart

For the button drag it to under override func didReceiveMemoryWarning(){} such that:

and on the pop up select Action. Call it btbutton and select connect.

We can now exit the Assistive mode, go full screen on ViewController.swift.

Now lets get coding :)

Creating the Graph

We are there. We can do actual coding. I am not going to screenshot everything or go line by line. I will put the code up on GitHub for you (at the bottom of this article). It will be very heavily commented so you can understand every line.

First thing we want to import charts. Go to the top of the document and type “import Charts” just under “import UIKit”.

Then we need to create an Array of doubles under the line “@IBOutlet weak var chtChart: LineChartView!”. I’m calling mine numbers.

Then we want to go down to

“@IBAction func btnbutton(_ sender: Any) {
}”

And get the input from the text field. Make it a double here. We are not going to sanitise any input, as that’s a lesson in its own — lets hope our users are going to be experts in Computer Science! We then want to add it numbers array.

We are then going to create an function called updateGraph() which will update the graph.

Here we want to make a dataset. This is going to be the data that the graph displays. The line is:

var lineChartEntry = [ChartDataEntry]()

We then want to do a for loop over every element in the array numbers.

Think of ChartDataEntry as the points on the graph you want the graph to draw between.

Here we get the vales out of the numbers out of the numbers array and add it to its own ChartDataEntry object before it gets add to the lineChartEntry.

Once that’s done we have all the values we want in lineChartEntry. We now just need to go through and create a line.

We create a new object (mine is called line 1) of LineChartDataSet. Set the label to “Number”. A LineChartDataSet is going to be the line inbetween all the lineChartEntry. This is done only once for each line and by this line

let line1 = LineChartDataSet(values: lineChartEntry, label: “Number”)

Lets set the colour blue. Do this by this line underneath the line above:

line1.colors = [NSUIColor.blue]

Here we can do some more awsome customisation to each line! Try some of your own such as circle colours.

We got 2 more lines to do! We need to create a LineChartData Object called data. This is the object that the chart will display. LineChartData will be the object that is plotted with all lines you want to display!

let data = LineChartData()

And we just add the line to the dataset by:

data.addDataSet(line1)

Finally, to add the data to the chart type:

chtChart.data = data

This line will cause an update to take place :)

We can then change the chartDescription to say My awsome graph. Add this line to the end:

chtChart.chartDescription?.text = “My awesome chart”

Your code should look a little like this (Don’t worry about the comments)

Run your app and you should have data showing up on the chart add a few values and see your graph display the values:

Who! If you can see this, well done, you did it! Your own line graph! Now you can go away and make it work off a database so it remembers its values, maybe remove the pink colour?

Feel free to use my code and use it to learn — break it, fix it or even turn it into a line graph!

Thanks for reading! Any comments or issues, you can comment here or make an issue on the GitHub page. I will try to get back to you.

Here is my GitHub Repository: — simply download it as a Zip and you’ll be fine :)

Thanks for reading! Any comments or issues, you can comment here or make an issue on the github page. I will try to get back to you.

Here is my github Repositry: — simply download it as a Zip and you’ll be fine :)

Sources:

Using Realm and Charts with Swift 3 in iOS 10 by Sami Korpela (would recommend a read for anyone wanting to do bar graphs)

Charts Demo for macOS

Thanks for the guys at https://github.com/danielgindi/Charts who have put my tutoral on the readme page of the repository.