如何在View Controller外部设置数据源和委托

时间:2015-01-15 00:12:24

标签: ios swift delegates datasource bemsimplelinegraph

这可能听起来像一个奇怪的问题,但我试图实现BEMSimpleLineGraph库来生成我在UITableView中放置的一些图形。我的问题是我如何引用外部dataSource和Delegate以在每个单元格中放置不同的图形(BEMSimpleLineGraph在UITableView和UICollectionView之后建模)。我现在有这样的事情:

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

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

    cell.userInteractionEnabled = false

    if indexPath.section == 0 {

        cell.graphView.delegate = GroundspeedData()
        cell.graphView.dataSource = GroundspeedData()
        return cell

    }
    if indexPath.section == 1 {

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

    }
    return cell
}

第1部分的我的dataSource和Delegate在此下方正确设置,并且GroundspeedData类如下所示:

class GroundspeedData: UIViewController, BEMSimpleLineGraphDelegate, BEMSimpleLineGraphDataSource {

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

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

由于某些原因,当我运行应用程序时,Xcode报告它找不到第0部分的dataSource,特别是"数据源不包含任何数据。"。我应该如何引用这个备用数据源?

1 个答案:

答案 0 :(得分:5)

    cell.graphView.delegate = GroundspeedData()
    cell.graphView.dataSource = GroundspeedData()

一个问题是:委托和数据源是弱引用。这意味着他们不会保留他们所设定的内容。因此,每条线都会创建一个GroundspeedData对象,它会在一阵烟雾中瞬间消失。您需要做的是创建一个GroundspeedData对象并保留它,然后将图表视图的委托和数据源指向它

另一个问题是:您是否打算创建一个 new GroundspeedData对象,或者在视图控制器层次结构中的其他地方使用的对象?因为GroundspeedData()创建了一个 - 没有视图也没有数据。您可能意味着使用对现有的引用。