A. K. M. Tariqul Islam
A. K. M. Tariqul Islam

Reputation: 2834

UITableView is not displaying data?

I took an UIViewController. Then brought a TableView into it. And then a TableViewCell in the tableview. I assigned identifier and custom table view cell class with that prototype cell. Also created necessary outlets. Then this is my parent view controller:

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
    }

}

But my table is empty. What am I missing?

Upvotes: 0

Views: 53

Answers (1)

NSNoob
NSNoob

Reputation: 5608

You have to add the following line in your viewDidLoad:

theTableView.dataSource = self

When you do that, you provide dataSource to your Tableview from your ViewController and then your TableView starts showing data.

The methods cellForRowAtIndexPath and rowsForSection are both Datasource methods. Since you haven't set your dataSource that's why your TableView fails to load the provided data.

Also if you haven't added the TableView via Storyboard/Xib, you also have to add it as a subview of your view.

Upvotes: 1

Related Questions