Search code examples
uitableviewswiftgraphbemsimplelinegraph

Setting up BEMSimpleLineGraph Plot within UITableView


While working on my app this evening I've come across a new situation. I'm attempting to load 2 different graphs [using BEMSimpleLineGraph] each into a different row of a UITableView. I've created a custom cell containing a UIView that inherits from BEMSimpleLineGraphView. My view controller naturally inherits from UIViewController, BEMSimpleLineGraphDelegate, BEMSimpleLineGraphDataSource, UITableViewDataSource, and UITableViewDelegate.

UITableViewDataSource and BEMSimpleLineGraphDataSource both have required methods but when I declare my table view's numberOfRowsInSection and cellForRowAtIndexPath methods, I can't place my numberOfPointsInLineGraph and valueForPointAtIndex methods inside of cellForRowAtIndexPath as this doesn't meet the requirements for BEMSimpleLineGraphDataSource.

Here is my current class:

import Foundation

class FlightsDetailViewController: UIViewController, BEMSimpleLineGraphDelegate, BEMSimpleLineGraphDataSource, UITableViewDataSource, UITableViewDelegate {

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 2
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let cell: FlightsDetailCell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as FlightsDetailCell

    cell.userInteractionEnabled = false

    cell.graphView.enableBezierCurve = true
    cell.graphView.enableReferenceYAxisLines = true
    cell.graphView.enableYAxisLabel = true
    cell.graphView.colorYaxisLabel = UIColor.whiteColor()

    cell.graphView.delegate = self
    cell.graphView.dataSource = self

    return cell

}

func lineGraph(graph: BEMSimpleLineGraphView!, valueForPointAtIndex index: Int) -> CGFloat {
    let data = [1.0,2.0,3.0,2.0,0.0]
    let data2 = [2.0,0.0,2.0,3.0,5.0]
    return CGFloat(data[index])
}

func numberOfPointsInLineGraph(graph: BEMSimpleLineGraphView!) -> Int {
    return 5
}
}

How would I for example have the first graph display the data from data and the second graph display data from data2. My graphs are displaying fine now but I can't figure out how to define independent data sets for each graph. How can this be done?


Solution

  • You need to check which instance of your graph is calling the datasource/delegate. You can find out by comparing the parameter lineGraph included in the datasource/delegate methods, to your instances of the graph.

    I'm not familiar enough with swift, be here is how you can do it in Objective-C.

    - (CGFloat)lineGraph:(BEMSimpleLineGraphView *)graph valueForPointAtIndex:(NSInteger)index 
    {
        if ([graph isEqual:self.myGraph1])
        {
            return data;
        }
        else
        {
            return data2;
        }
    }