2016-08-01 68 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,则还必须将其添加为视图的子视图。