Can't make UiTableView work

2019-08-30 09:54发布

问题:

I am working on a project on XCode 6 and Swift. I need to add a UITableView to a UIViewController, and then fill the table with content.

So, on my default UIViewController, I added a UITableView and a UITableViewCell (using the storyboard). Next, I set the UIViewController as the dataSource and delegate for the table.

Finally, I added this code to my view controller.swift:

import UIKit

class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet var table: UITableView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


override func numberOfSectionsInTableView(tableView: UITableView) -> Int {

    return 1


}


override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{

    return 3
}



override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

     let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell

    cell.textLabel?.text = "Hello world"

    table.reloadData()

    return cell


}

However, as I run the project, I get a crash with the following log

2015-04-08 21:06:52.820 tableViewTest[12380:783945] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UITableViewController loadView] loaded the "BYZ-38-t0r-view-8bC-Xf-vdC" nib but didn't get a UITableView.'

I've tried anything, I really don't know how to solve this.

Can anyone help me?

回答1:

You have a tableview as IBOutlet and you need your ViewController to be a subclass of UIViewController.

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {}


回答2:

Seems to me that you're using an UIViewController in the storyboard but referencing an UITableViewController in the code. Try changing

class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {

to

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

and put table.reloadData() in the viewDidLoad function.