Swiftpack.co - highcharts/highcharts-ios as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
highcharts/highcharts-ios
iOS wrapper for Highcharts.
.package(url: "https://github.com/highcharts/highcharts-ios.git", from: "v9.2.2")

Highcharts

Carthage compatible

Highcharts iOS is a delightful wrapper of HighchartsJS for iOS.

The most popular, robust and battle-tested JavaScript Charting library is now available for iOS with our new Objective-C wrapper. Get gorgeous, multi-touch charts with minimal effort.

Documentation

Access the full API documentation here.

HOWTO

Here we present how to create basic chart and place it in your project.

What we need to do

  • Prepare your project for Highcharts
  • Create chart view and place it in your view
  • Create chart options and add them to your chart view
  • Run your app and enjoy!

Preparing your project

  • First of all download Highcharts xcframework from here: Highcharts or by using Cocoapods by adding

    pod 'Highcharts', '~> 9.2.2'
    

    to your Podfile

    or Carthage by adding

    github "https://github.com/highcharts/highcharts-ios" >= 9.2.2
    

    to your Cartfile

    or Swift Package Manager by adding package dependency

    https://github.com/highcharts/highcharts-ios
    
  • Now add Highcharts to your project by simply copying it to your project to folder Frameworks (create it if necessary) and remeber to check "Copy items if needed" option

alt text

  • Click on finish

alt text

  • Then go to your project settings and add Highcharts to Frameworks, Libraries, and Embedded Content with "Embed & Sign" option

alt text

  • If your project is leveraging Xcode UI testing, make sure you add the Highcharts framework to Embedded Binaries for the UITests target as well as the main project target

You are now set to use Highcharts!

Please note when linking manually that binary framework in the 'release' directory is designed to allow uploads to the AppStore. Therefore it does not allow running on iOS Simulator. In order to use simulator, download the repository and use framework that can be found in the 'development' directory. Cocoapods/SPM/XCFramework solve this problem automatically - they introduce a stripping script for AppStore uploads.

Using Highcharts (demo app)

Set AppDelegate

In your AppDelegate.swift import Highcharts at the top

import Highcharts

Add this line to your application:didFinishLaunchingWithOptions method:

HIChartView.preload()

Add HIChartView to your View Controller

In your View Controller .swift file add

import Highcharts

and

var chartView: HIChartView!

Creating chart

Let's start with creating simple chart!

For the purpose of this tutorial, we will create a simple column chart using random data.

In viewDidLoad add following lines

chartView = HIChartView(frame: CGRect(x: view.bounds.origin.x, y: view.bounds.origin.y  +  20, width: view.bounds.size.width, height: 300))

This will create our chartView with defined origin and size.

Done! Now let's create a chart.

The heart of a chart is HIOptions class which contains all the information needed to present it. Some of the options there are optional, some are not (see demo app HighFit provided by Highcharts).

Create instance of HIOptions class

let options = HIOptions()

Now we need to add the options that our chart requires to be presented. Let's start with chart type. To do so, create HIChart class object and set its type to "column"

let chart = HIChart()
chart.type = "column"

Add this object to your options

options.chart = chart

Then let's give our chart a name (title) and also add it to options

let title = HITitle()
title.text = "Demo chart"
options.title = title

Now we need to add some data (in this tutorial it will be some random set of numbers). Since we are creating a column chart, we need to use HIColumn data series

let series = HIColumn()

To add data, just create array of our data objects

series.data = [49.9, 71.5, 106.4, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]

Since options can store multiple series, we need to add our series as one-element-array

options.series = [series]

And at last add our options to the chartView

chartView.options = options

Don't forget to add chartView as subview to your View Controller's view! At the end add

view.addSubview(chartView)

That's it! We are now set to run our application! Your View Controller .m file should look like this

import Highcharts
import UIKit

class ViewController: UIViewController {

  var chartView: HIChartView!

  override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    chartView = HIChartView(frame: CGRect(x: view.bounds.origin.x,
                                          y: view.bounds.origin.y + 20,
                                          width: view.bounds.size.width,
                                          height: 300))

    let options = HIOptions()

    let chart = HIChart()
    chart.type = "column"
    options.chart = chart

    let title = HITitle()
    title.text = "Demo chart"
    options.title = title

    let series = HIColumn()
    series.data = [49.9, 71.5, 106.4, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    options.series = [series]

    chartView.options = options

    view.addSubview(chartView)
  }

}

Press "Run" in XCode.

For more complex solutions see demo app HighFit provided by Highcharts or read the following documentation!

Additional info

Additional modules

In case of enabling additional module, add it to plugins of HIChartView object before assign your chart options, e.g.

chartView.plugins = ["annotations"]
...
chartView.options = options

HIColor example

Highcharts iOS wrapper provides its own colors implementation. As you can notice, some options are of HIColor type. You can instantiate the desired color in few ways which are described in the API documentation. In here, we will show the most complex case which is gradient usage. For example, you can instantiate a color for chart background:

chart.backgroundColor = HIColor(linearGradient: ["x1": 0, "x2": 0, "y1": 0, "y2": 300],
                                stops: [
                                  [0, "rgb(102, 153, 161)"],
                                  [1, "rgb(128, 135, 232)"]
                                ])

HIFunction example

Thanks to Highcharts iOS wrapper you can now assign native iOS closures to events for specific chart elements. We will show you a small taste of such usage. For these purpose we will let appear a simple alert with point coordinates when it's clicked but keep in mind that you can achieve much more with HIFunction mechanism!

First of all, you need to create a plotOptions object for your series type:

let plotOptions = HIPlotOptions()
plotOptions.series = HISeries()

Now, you can refer to the point event and add on click function like this:

plotOptions.series.point = HIPoint()
plotOptions.series.point.events = HIEvents()
    
let clickFunction = HIFunction(closure: { [weak self] context in
  guard let self = self, let context = context else { return }

  let category = context.getProperty("this.category") ?? "",
      value = context.getProperty("this.y") ?? ""

  let alertMessage = "Category: \(category), value: \(value)"

  let alertController = UIAlertController(title: nil,
                                          message: alertMessage,
                                          preferredStyle: .alert)

  let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
  alertController.addAction(okAction)

  self.present(alertController, animated: true, completion: nil)
}, properties: ["this.category", "this.y"])

plotOptions.series.point.events.click = clickFunction

options.plotOptions = plotOptions

As you can see in the above code snippet first argument of the HIFunction is the actual closure. Second argument is simple string array of chart elements. We need to put them here to let wrapper pull them for us during HIFunction instantiation. Thanks to this, we can refer to these elements corresponding values by getProperty: method. You can pull any data from chart like this. Depending on the current needs you can just run some code, withdraw data from chart, return a String to the chart (e.g. in HITooltip formatter) and even put pure Javascript function in the constructor in the String format. For more information feel free to check the API documentation.

Custom fonts

Highcharts iOS wrapper allows you to add custom fonts. If you have your own font and want to use that in your chart, follow next steps:

  • Add a font file to your project. Select File -> Add Files to “Your Project Name” from the menu bar or drag and drop the file into your Xcode project, check Copy items if needed option and add the font to your app target.

alt text

alt text

  • Add your font to HIChartView. To do this, firstly, you need to get an absolute path pointing to the location of the font and then call addFont: method:
let fontPath = Bundle.main.path(forResource: "Windsong", ofType: "ttf")
HIChartView.addFont(fontPath)

So, now you can use a custom font in your chart. For example, let's change the chart title font. You only need to create a style object for the title and set its font family to the font file name:

title.style = HICSSObject()
title.style.fontFamily = "Windsong"

GitHub

link
Stars: 114
Last commit: 3 weeks ago

Ad: Job Offers

iOS Software Engineer @ Perry Street Software
Perry Street Software is Jack’d and SCRUFF. We are two of the world’s largest gay, bi, trans and queer social dating apps on iOS and Android. Our brands reach more than 20 million members worldwide so members can connect, meet and express themselves on a platform that prioritizes privacy and security. We invest heavily into SwiftUI and using Swift Packages to modularize the codebase.

Submit a free job ad (while I'm testing this). The analytics numbers for this website are here.

Release Notes

v9.2.2
3 weeks ago

Version 9.2.2

Framework:

  1. Improved ES module architecture with support for tree shaking of the most commonly used modules. See #8667.
  2. Added new feature, series.relativeXValue, allowing point X values to be relative to the series.pointStart and subject to series.pointInterval and series.pointIntervalUnit.
  3. Added internal support for Google Sheets API v4, fixing stability problems with loading data from spreadsheets.

Framework upgrade notes:

  1. Existing setups with Google Sheets stopped working in August 2021 as Google phased out version 3 of their Google Sheets API. Highcharts has now been upgraded to version 4 of the API, but this will not work unless an API key is given in the data.googleAPIKey option. See the comprehensive tutorial from Hands-On Data Visualization on how to obtain the key. Additionally, data.googleSpreadsheetWorksheet is deprecated and replaced by data.googleSpreadsheetRange, which allows for more detailed instructions on what data to load.

Framework bug fixes:

  1. Fixed #15938, charts still crashed in some legacy browsers where Intl was missing.
  2. Fixed #15235, whitespace between HTML elements got removed.
  3. Fixed #15986, accessibility exit anchor disappeared on Chart.update.
  4. Fixed #15229, accessibility region labels were sometimes duplicated.
  5. Fixed #16119, touch scrolling was blocked after zooming when single-finger panning was not enabled.
  6. Fixed #16146, negative values broke sunburst chart.
  7. Fixed #16153, fontFamily reset when updating chart.style.
  8. Fixed #16126, printing chart in full screen with accessibility loaded threw.
  9. Fixed #16112, axis options set by setOptions were not picked up by polar chart when chart axis options were set as an array.
  10. Fixed #16104, chart warned about unsorted data when updating category names.
  11. Fixed #14143, #14434, #13310, tooltip with stickOnContact and useHTML or outside enabled did not work properly.
  12. Fixed #16080, #13705, sankey chart with self-referential points broke on redraw.
  13. Fixed #16084, #13671, updating timeline chart did not work properly in some cases.
  14. Fixed #15334, some waterfall data labels did not show for points below threshold.
  15. Fixed #16062, lines after the first line break in text with useHTML set to true were misaligned in exported charts when exporting.allowHTML was set to false.
  16. Fixed #16053, color axis disappeared after toggling legend.
  17. Fixed #16044, draggable point guide box was not big enough when the point was partially outside the end of the axis.
  18. Fixed #16042, 1px gaps showed between some xrange points when there was no gaps in the data.
  19. Fixed #1441, datetime axis ticks did not get date/time formatting applied when tickPositions were set.
  20. Fixed #15777, plot line labels were not clipped.
  21. Fixed #13840, 3d column chart with scrollbar showed points outside plot in upper left corner.
  22. Fixed #15983, event did not get removed when updating it to undefined.
  23. Fixed #15973, word cloud focus border position for rotated points was wrong in Firefox.
  24. Fixed #12015, linked series did not get inactive state applied when hovering legend item.
  25. Fixed #15946, unchanged markers set in options did not animate when updating data through update.
  26. Fixed #15449, HTML in exporting menu item text did not work.
  27. Fixed #15922, heatmap data labels with useHTML enabled and default formatter did not work, per-point borderColor and borderWidth did not work.
  28. Fixed #15902, legend proxy buttons did not update when updating series.
  29. Fixed 3d bug, z-axis updated twice on Chart.update.
  30. Fixed #15862, Chart.update with oneToOne attempting to remove pane threw.
  31. Fixed #9047, boosted series with null points showed warnings in some browsers.
  32. Fixed #5430, marker shown on hover with disabled markers missed CSS class.
  33. Fixed #15909, pie point with visible set to false and useHTML data labels threw.
  34. Fixed additional case for #15235, nested whitespace got removed in HTML.
  35. Fixed #16231, a regresssion in v9.2 causing exporting not to work with styledMode enabled.

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics