首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在视图控制器之外设置数据源和委托

如何在视图控制器之外设置数据源和委托
EN

Stack Overflow用户
提问于 2015-01-15 00:12:24
回答 1查看 2.5K关注 0票数 1

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

代码语言:javascript
复制
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类如下所示:

代码语言:javascript
复制
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,特别是“数据源不包含数据”。否则我应该如何引用这个备用dataSource?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-15 00:16:13

代码语言:javascript
复制
    cell.graphView.delegate = GroundspeedData()
    cell.graphView.dataSource = GroundspeedData()

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

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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27954822

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档