这听起来像是一个奇怪的问题,但我正在尝试实现 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/