quickstart Swift

Introduction

Note: This guide has been written in Swift 3

This is a brief introduction to using the ShinobiCharts component with the Swift programming language. This quick start guide will walk you through a series of simple steps introducing the key features of the charting library, which includes supplying data to the chart via the datasource, simple styling and configuration of the labels, title and axes.

At the end of this guide you will have created the following chart:

What we're aiming for

Your Download

The ‘ShinobiCharts’ folder contains:

  • A copy of the framework.
  • A copy of the documentation for the framework.
  • A set of samples to demonstrate getting started with ShinobiCharts.
  • A README file with setup steps.
  • A change log stating the changes made in each release.
  • A copy of the ShinobiControls Licence.
  • A text file containing the version number of the framework.

Setting up the project

Start-up Xcode and create a new project via File / New / Single View Application. On the next screen that appears, be sure to select “Swift” as the language to use for your new project.

Creating a swift project

Within your newly created project add a reference to the ShinobiCharts framework by dragging the framework from the Finder into the project.

ShinobiCharts makes use of a few other frameworks, so add the following as well:

  • libc++.tbd

Adding a Chart

If you’re using a trial framework, ensure you check “Keychain Sharing” under your app’s Capabilities tab, in the project settings.

Firstly we will need to import the library into our project. Open up the ViewController.swift file and at the top add the import:

import ShinobiCharts

The next step is to create an instance of the chart and add it to the view. Again open up the ViewController.swift file and update the viewDidLoad() method:

let margin = (UIDevice.current.userInterfaceIdiom == .phone) ? CGFloat(20) : CGFloat(50)
let chart = ShinobiChart(frame: view.bounds.insetBy(dx: margin, dy: margin))
chart.title = "Trigonometric Functions"

This instantiates the chart object, and sets its title. Note that the margin around that chart depends on the device form factor. A smaller margin is used on iPhone devices. The ShinobiChart object is a UIView subclass, so respects resizing masks and auto-layout. Further down the same method add the following:

chart.autoresizingMask = [.flexibleHeight, .flexibleWidth]

This ensures that the chart frame is adjusted when the device orientation changes. Alternatively, you could use AutoLayout to position your chart as you wish.

If you have downloaded a trial version of the ShinobiCharts you will have been issued with a trial key. Add the key that you were supplied with at the location indicated below.

ShinobiCharts.trialKey = "" // TODO: add your trial key here!

The next step is to add the axes to the chart. In this example both the X and Y axes are linear, although the chart also supports date-time and category axes. Further down the same method add the following:

// add a pair of axes
let xAxis = SChartNumberAxis()
xAxis.title = "X Value"
chart.xAxis = xAxis

let yAxis = SChartNumberAxis()
yAxis.title = "Y Value"
chart.yAxis = yAxis

Now that the chart is configured, the final step is to add it to the view. Add the following to the end of the method:

view.addSubview(chart)

Before you can see the chart in action, you need to supply some data, which brings us onto the next step …

Adding a Datasource

In order to render your data within the chart you need to supply a ‘datasource’, this is a class that adopts the SChartDatasource protocol methods.

If you have worked with UITableView the idea of a datasource should be familiar to you. The shinobichart shares the same concepts both of a datasource, for supplying data, and a delegate, for reacting to user interactions.

Within ViewController.swift, adopt the datasource protocol via the class extension, that Xcode generated for you, as follows:

class ViewController: UIViewController, SChartDatasource {

The SChartDatasource protocol has four required methods. We’ll take a look at each of them in turn.

The first method numberOfSeries(in:) is used to inform the chart how many series you wish to render. Add the following implementation, with a hard-coded value of two:

func numberOfSeries(in chart: ShinobiChart) -> Int {
    return 2
}

The next method, seriesAtIndex is used to supply each series to the chart. The series objects describe the visual appearance of each series, but not their actual data values. Add the following to the view controller in order to return two different line series:

func sChart(_ chart: ShinobiChart, seriesAt index: Int) -> SChartSeries {
    let lineSeries = SChartLineSeries()

    if index == 0 {
        lineSeries.title = "y = cos(x)"
    } else {
        lineSeries.title = "y = sin(x)"
    }

    return lineSeries
}

The next method, sChart(numberOfDataPointsForSeriesAt:), is used to specify the number of data points within a specific series. Add the following implementation below:

func sChart(_ chart: ShinobiChart, numberOfDataPointsForSeriesAt seriesIndex: Int) -> Int {
    return 100
}

In this example, both series have 100 points, but they do not have to have the same number.

The last method required by the protocol is sChart(_:dataPointAt:forSeriesAt), which the chart uses to request the value of each individual datapoint for each series. The returned datapoint must adopt the SChartData protocol, which specifies xValue and yValue properties. The charting framework supplies a concrete implementation of this protocol, SChartDataPoint, however, you have the option of implementing this protocol with your own data-objects in order to avoid the need to maintain two copies of your data.

Add the following implementation:

func sChart(_ chart: ShinobiChart, dataPointAt dataIndex: Int, forSeriesAt seriesIndex: Int) -> SChartData {
    let datapoint = SChartDataPoint()

    // both functions share the same x-values
    let xValue = Double(dataIndex) / 10.0
    datapoint.xValue = xValue

    // compute the y-value for each series
    if seriesIndex == 0 {
        datapoint.yValue = cos(Double(xValue))
    } else {
        datapoint.yValue = sin(Double(xValue))
    }

    return datapoint
}

Now that the datasource is implemented, you can add the following to viewDidLoad:

chart.datasource = self

At this point if you build and run, you should see a couple of series:

Basic chart

Adding Labels and Basic Styling

The chart in its current state is a little plain! This section will build on the simple chart that you have created and add a bit more style.

Firstly, the axes could do with having some labels. Also, the Y axis could do with a bit of padding around the top and bottom values to make it easier to see the top and bottom of the curves.

Open up ViewController.m and edit the axis creation code as follows:

let xAxis = SChartNumberAxis()
xAxis.title = "X Value"
chart.xAxis = xAxis

let yAxis = SChartNumberAxis()
yAxis.title = "Y Value"
yAxis.rangePaddingLow = 0.1
yAxis.rangePaddingHigh = 0.1
chart.yAxis = yAxis

It would be nice to see the legend on the iPad, where there is much more screen space to play with. Add the following to the viewDidLoad() method:

chart.legend.isHidden = UIDevice.current.userInterfaceIdiom == .phone

One of the most powerful features of shinobicharts is its gesture-based interactions. Enable panning and zooming on each axis by adding the following code:

yAxis.enableGesturePanning = true
yAxis.enableGestureZooming = true
xAxis.enableGesturePanning = true
xAxis.enableGestureZooming = true

These properties allow the user to pan the chart with a single-finger pan gesture, and zoom using two-finger pinch.

Finally, enable area fill by adding the following just after each series is created:

lineSeries.style().showFill = true

To color the fill area and make it transparent to allow the user to see both series, add this just below lineSeries.title = "y = cos(x)";:

lineSeries.style().areaColor = UIColor.blue.withAlphaComponent(0.5)
lineSeries.style().areaColorLowGradient = UIColor.blue.withAlphaComponent(0.8)

And this just below lineSeries.title = "y = sin(x)":

lineSeries.style().areaColor = UIColor.green.withAlphaComponent(0.5)
lineSeries.style().areaColorLowGradient = UIColor.green.withAlphaComponent(0.8)

Each series has a style object associated with it, where the style type depends on the series type. A line series has a style object of type SChartLineSeriesStyle. These objects have a number of properties which you can adjust including line color, thickness and the colors used for gradient fill.

To see the effect of the few simple changes you have just made, build and run:

The result

Now that you have created a simple chart, why not have a go at creating a column, or pie chart?