beauchette
beauchette

Reputation: 1126

Swift table view not showing contents

I wanted to give a go at swift, and looked at several tutorials. I tried to implement a TableView.

Here is my code :

import UIKit

class ViewController:  UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var tableView: UITableView!

    var items: [String] = ["lol1", "lol2", "lol3"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1;
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.items.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")!

        cell.textLabel?.text = self.items[indexPath.row]

        return cell
    }

    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        print("You selected cell #\(items[indexPath.row])!")
    }

}

MY IBOutlet is connect to the tableview I inserted in the storyboard.

When I run it, I have a TableView, but it's missing contents.

From what I gathered through some (more or less outdated) tutorials, I shouldn't have anything more to do, what am I missing ?

Upvotes: 0

Views: 90

Answers (2)

SGDev
SGDev

Reputation: 2252

Where are you set dataSource and Deleagte methods of TableView?

use this code

 override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.tableView.dataSource = self
        self.tableView.delegate = self
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    }

Upvotes: 2

vadian
vadian

Reputation: 285064

2 possible reasons:

  1. If the cell is designed as prototype cell you must not register the cell.
  2. dataSource and delegate of the table view must be connected to the controller in Interface Builder or set in code.

Upvotes: 1

Related Questions