tahoecoop tahoecoop - 1 year ago 126
Swift Question

How to implement iOS Chart in a tableview cell?

I'm using iOS Charts (https://github.com/danielgindi/ios-charts) and it works great in a normal view controller. However, I want to implement these charts in a tableview cell where the data source will be different depending on the cell. Also, the outlet to the view that is displaying this chart is in my cell subclass. How do I implement this code (where it works in a non-repeating view controller) to display in a view in my cell subclass? Thanks in advance!!

class ChartViewController: UIViewController {

@IBOutlet weak var lineChartView: LineChartView!

override func viewDidLoad() {

let candidates = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
let ratings = [33.0, 20.0, 13.0, 9.0, 8.0, 6.0]

setChart(candidates, values: ratings)

func setChart(dataPoints: [String], values: [Double]) {

var dataEntries: [ChartDataEntry] = []

for i in 0..<dataPoints.count {

let dataEntry = ChartDataEntry(value: values[i], xIndex: i)


let lineChartDataSet = LineChartDataSet(yVals: dataEntries, label: "Rating")
let lineChartData = LineChartData(xVals: dataPoints, dataSet: lineChartDataSet)
lineChartView.data = lineChartData
lineChartView.animate(xAxisDuration: 2.0)

Answer Source

You can set up the cell view for your table view cell subclass so that you can use the LineChartView in the storyboard by copying everything from your view controller into a prototype table view cell.

Remember to set the class of your custom cell in the storyboard’s Identity Inspector.

Add some properties to hold the parameters of your chart. These can be set when you bring up the cell in cellForRowAtIndexPath:.

For example:

class MyTableViewCell: UITableViewCell {
    @IBOutlet weak var lineChartView: LineChartView!
    var candidates: Array<String>?
    var ratings: Array<Float>?

When you bring up the cell, the properties can be set:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {        
    let cell = tableView.dequeueReusableCellWithIdentifier(“chartCell”, forIndexPath: indexPath)
    candidates = someCandidatesArrayForIndexPath(indexPath)
    ratings = someRatingsArrayForIndexPath(indexPath)
    return cell

Therefore, when you return the cell it will have the properties set to show a different view based on its index path. The functions someCandidatesArrayForIndexPath( ) and someRatingsArrayForIndexPath( ) that I have used in the example obtain the values needed to be displayed. You will have to write these functions.