[英]How to set datasource and delegate Outside of View Controller
This might sound like an odd question but I'm trying to implement the BEMSimpleLineGraph library to generate some graphs that I have place in a UITableView. 这听起来像是一个奇怪的问题,但是我试图实现BEMSimpleLineGraph库以生成一些放置在UITableView中的图形。 My question is how I reference an external dataSource and Delegate to have different graphs placed in each cell (BEMSimpleLineGraph is modelled after UITableView and UICollectionView). 我的问题是我如何引用外部dataSource和Delegate在每个单元格中放置不同的图形(BEMSimpleLineGraph是在UITableView和UICollectionView之后建模的)。 I currently have something like this: 我目前有这样的事情:
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
}
My dataSource and Delegate for section 1 is setup properly below this and the GroundspeedData class looks like this: 我的第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
}
}
For some reason when I run the app, Xcode reports that it cannot find the dataSource for section 0, specifically "Data source contains no data.". 由于某种原因,当我运行该应用程序时,Xcode报告它找不到第0部分的数据源,特别是“数据源不包含任何数据”。 How should I otherwise reference this alternate dataSource? 我应该如何另外引用此备用数据源?
cell.graphView.delegate = GroundspeedData()
cell.graphView.dataSource = GroundspeedData()
One problem is: the delegate and data source are weak references. 一个问题是:委托和数据源是弱引用。 That means they do not retain what they are set to. 这意味着他们不会保留设置的内容。 Thus, each of those lines creates a GroundspeedData object which instantly vanishes in a puff of smoke. 因此,这些行中的每一行都会创建一个GroundspeedData对象,该对象会立即消失在烟雾中。 What you need to do is make a GroundspeedData object and retain it , and then point the graph view's delegate and data source to it . 您需要做的是创建一个GroundspeedData对象并保留它 ,然后将图形视图的委托和数据源指向它 。
Another problem is: do you intend to create a new GroundspeedData object or use one that exists already elsewhere in your view controller hierarchy? 另一个问题是:您打算创建一个新的 GroundspeedData对象还是使用视图控制器层次结构中其他地方已经存在的对象? Because GroundspeedData()
creates a new one - with no view and no data. 因为GroundspeedData()
创建了一个新视图-没有视图且没有数据。 You probably mean to use a reference to the existing one. 您可能打算使用对现有参考文献的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.