2015-01-15 19 views
1

這可能聽起來像一個奇怪的問題,但我想實現BEMSimpleLineGraph庫生成一些圖形,我已經放在UITableView中。我的問題是我如何引用一個外部數據源和委託在每個單元格中放置不同的圖形(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是正確安裝下面這和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的數據源,特別是「數據源不包含數據」。我應該如何以其他方式引用此備用數據源?

回答

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

一個問題是:委託和數據源是弱引用。這意味着他們不會保留他們所設定的。因此,每條線都會創建一個GroundspeedData對象,該對象立即在一縷煙霧中消失。你需要做的是創建一個GroundspeedData對象並保留它,然後將圖形視圖的代表和數據源指向它

的另一個問題是:你打算創建一個新 GroundspeedData對象或使用一個在您的視圖控制器層次別處存在已經?由於GroundspeedData()創建了一個新的一個 - 沒有看法和沒有數據。您可能的意思是使用對現有之一的參考。

+0

如果我猜測你的問題在於你沒有掌握_instantiating_類和獲得對該類的_existing_實例的引用之間的區別,我新的Swift教程有一個關於這個問題的部分:http: //www.apeth.com/swiftBook/ch04.html#_instance_references – matt

+0

我有上面顯示的G​​roundspeedData類,並且我想要問我的graphView(特定部分)是否將它從該類中委託給它和數據源。那有意義嗎?數據已經在課程中,我只需要訪問它。 – user3185748

+0

不,@ user3185748,不存在「數據已經在課堂上」這樣的事情。數據位於類的_instance_中。這是你沒有把握的整個概念。 – matt

相關問題