search by tags

for the user

adventures into the land of the command line

adding a table view to a view controller with swift 2

If you are trying to implement a table view inside a view controller, you need to add a bunch of functions that are already put in place if you were to just use the tableview controller.

If you don’t do this, you will see an error like this:

‘ViewController’ does not conform to protocol ‘UITableViewDataSource’ 

Make sure you have all of these things:

class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

  @IBOutlet weak var tableViewMenu: UITableView!

  override func viewDidLoad() {
    super.viewDidLoad()
    tableViewMenu.dataSource = self
    tableViewMenu.delegate = self
    tableViewMenu.registerClass(UITableViewCell.self, forCellReuseIdentifier: "someCellIdentifier")
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var count:Int?
    if something {
      count = 10 or whatever
    }
    return count!
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    cell = self.tableViewMenu.dequeueReusableCellWithIdentifier("someCellIdentifier", forIndexPath: indexPath)
    return cell!
  }

  func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    ... something you want to happen when the user selects the cell
  }
}

“someCellIdentifier” should be an identifier you set for a prototype cell. Clicking on the prototype cell, then on the attribute inspector will let you set the identifier.