2014-12-25 60 views
0

當我使用UITableViewController創建tableView時,會得到很多覆蓋函數,但是當您使用常規的UIViewController時,使用這些覆蓋函數時會出錯,將其改爲常規功能。我相信這就是爲什麼我的核心數據不會加載到我的單元格中,並試圖使用viewDidLoad函數來加載我的數據。Swift - 在UIViewController中覆蓋函數與UITableViewController

我知道我的代碼應該工作,因爲我所要做的就是將所有代碼從UITableViewController轉移到UIViewController,並且我的代碼在我的UITableViewController中工作。

我迄今爲止的努力:

override func viewDidLoad() { 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     // Configure the cell... 

     let CellID:NSString = "CELL" 

     var cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell 

     if let ip = indexPath as Optional { 

      var data:NSManagedObject = myList[ip.row] as NSManagedObject 
      cell.textLabel!.text = data.valueForKeyPath("username") as? String 
     } 

     return cell 
    } 
} 

是覆蓋功能我細胞是空的原因,還是有其他方面的使用普通的UIViewController表現出的tableView什麼時候?

任何建議,將不勝感激。

回答

1

(1)你必須添加UITableViewDelegate到類,以便訪問的委託方法,例如:

class ViewController: UIViewController, UITableViewDelegate { 

添加UITableViewDelegate到下課後,您UITableView委託函數應該自動完成。

此外,請務必將UITableView的代表設置爲self,以便讓委託方法填充表格。

(2)現在,您的cellForRowAtIndexPath方法是您的viewDidLoad。移動它,使其不包含在任何其他方法中。

+0

我已經添加了UITableViewDelegate,正如我所說的應用程序運行,它只是不填充表。我也嘗試過viewDidLoad之外的cellForRowAtIndexPath函數,但是這不起作用。至於把代表設置爲「自我」,我不太清楚你的意思,所以我不能回答這個問題。但正如我所說,我所做的只是將我的代碼從tableViewController轉移到viewController,添加了UITableViewDelegate並在某些函數前刪除了「覆蓋」。 – martin

+0

@ frank21 1.您需要「覆蓋」。現在您已經添加了UITableViewDelegate,請嘗試再次輸入tableview委託函數。他們應該自動完成以包含覆蓋。 –

+0

2.您需要以編程方式將tableview的委託設置爲self(即'self.tableView.delegate = self')或使用界面構建器,例如:http://stackoverflow.com/a/19216613/2274694 –