2016-08-01 71 views
0

我參加了UIViewController。然後帶入TableView。然後在tableview中輸入一個TableViewCell。我爲該原型單元分配了identifier和自定義表格視圖單元類。還創建了必要的網點。那麼這是我的父視圖控制器:UITableView不顯示數據?

class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 

    @IBOutlet weak var theTableView: UITableView! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     // Do any additional setup after loading the view. 

//  let cell = MyTableViewCell() 
//  cell.optionText = UILabel() 
//  cell.optionText?.text = "testing..." 

//  theTableView.addSubview(cell) 
     theTableView.delegate = self 
    } 

    override func didReceiveMemoryWarning() { 
     super.didReceiveMemoryWarning() 
     // Dispose of any resources that can be recreated. 
    } 


    /* 
    // MARK: - Navigation 

    // In a storyboard-based application, you will often want to do a little preparation before navigation 
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
     // Get the new view controller using segue.destinationViewController. 
     // Pass the selected object to the new view controller. 
    } 
    */ 



    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return 5 
    } 

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! MyTableViewCell 
     cell.optionText.text = "hello..." 
     return cell 
    } 

} 

但我的表是空的。我錯過了什麼?

+0

你的意思是不是'theTableView.dataSource = self'? – NSNoob

+0

哦,我的不好:) ... –

回答

1

您必須添加下面的行放在viewDidLoad

theTableView.dataSource = self 

當你做到這一點,您將泰伯維從您的視圖控制器提供數據源,那麼你的TableView開始顯示數據。

方法cellForRowAtIndexPathrowsForSection都是數據源方法。由於您尚未設置數據源,因此您的TableView無法加載提供的數據。

另外,如果您還沒有通過Storyboard/Xib添加TableView,則還必須將其添加爲視圖的子視圖。