【问题标题】:UITableView is not displaying data?UITableView 不显示数据?
【发布时间】:2016-08-01 05:50:01
【问题描述】:

我拿了一个UIViewController。然后将TableView 带入其中。然后在表格视图中添加TableViewCell。我为该原型单元分配了identifier 和自定义表格视图单元类。还创建了必要的网点。然后这是我的父视图控制器:

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
    }

}

但是我的桌子是空的。我错过了什么?

【问题讨论】:

  • 你的意思不是theTableView.dataSource = self?

标签: ios swift uitableview


【解决方案1】:

您必须在viewDidLoad 中添加以下行:

theTableView.dataSource = self

当你这样做时,你从你的 ViewController 向你的 Tableview 提供数据源,然后你的 TableView 开始显示数据。

cellForRowAtIndexPath 和 rowsForSection 方法都是 Datasource 方法。由于您尚未设置数据源,这就是您的 TableView 无法加载提供的数据的原因。

此外,如果您没有通过 Storyboard/Xib 添加 TableView,您还必须将其添加为视图的子视图。

【讨论】:

    猜你喜欢
    • 2011-01-25
    • 2011-11-01
    • 2017-05-29
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 2013-11-13
    • 1970-01-01
    相关资源
    最近更新 更多