ios - 如何在 View Controller 之外设置数据源和委托(delegate)

标签 ios swift delegates datasource bemsimplelinegraph

这听起来像是一个奇怪的问题,但我正在尝试实现 BEMSimpleLineGraph 库以生成一些我放在 UITableView 中的图形。我的问题是我如何引用外部数据源和委托(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 部分的我的数据源和委托(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 部分的数据源,特别是“数据源不包含数据”。我应该如何引用这个备用数据源?

最佳答案

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

一个问题是:委托(delegate)和数据源是弱引用。这意味着他们不会保留他们设置的内容。因此,这些行中的每一行都会创建一个 GroundspeedData 对象,该对象会立即消失在一阵烟雾中。您需要做的是创建一个 GroundspeedData 对象并保留它,然后将图 TableView 的委托(delegate)和数据源指向它

另一个问题是:您打算创建一个 GroundspeedData 对象还是使用 View Controller 层次结构中已经存在的对象?因为 GroundspeedData() 创建了一个新的 - 没有 View 也没有数据。您可能想使用对现有的引用。

关于ios - 如何在 View Controller 之外设置数据源和委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27954822/

相关文章:

iphone - 对将 Class 方法与具有委托(delegate)的对象一起使用感到困惑

iOS - 我可以在使用 Callkit 接听电话时打开我的 VoIP 应用程序吗?

ios - 为 UITableViewController 执行与核心数据联合的等效操作

ios - delegate = self 导致线程 1 : Fatal error: Unexpectedly found nil while unwrapping an Optional value

swift - 如何创建增量数字字符串?

iphone - 调用按钮操作时 EXC_BAD_ACCESS(代码 = 2 或代码 1)

ios - 带有委托(delegate)的 objective-c 文本字段不起作用

ios - 清除完整的 Realm 数据库

ios - 数组对象加载但未连接到单元格

ios - 如何从共享扩展中的主容器项目导入文件?