Xcode beginner having run time error on simple tab

2019-09-07 02:39发布

问题:

I am learning how to use a table based app using Simon NG Swift Programming guide. I typed in the code verbatim and the Xcode environment gets stuck on the let cell = tableView line of code.

Can someone tell me what I am doing wrong?

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {


    var restaurantNames = ["Cafe Deadend", "homei", "teakha", "cafe loius", "petite oyster", "royal oak", "for knee rest",
        "jimmy johns", "mickey dee", "daddies big burgers"]



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

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

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

        // configure the cell
        cell.textLabel?.text = restaurantNames[indexPath.row]
        return cell
    }



    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.
    }


}

回答1:

The first error I saw when running your code is this:

2015-02-17 16:28:05.645 delete-me-maps[8008:151860] *** Terminating app due 
to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to 
dequeue a cell with identifier Cell - must register a nib or a class for the 
identifier or connect a prototype cell in a storyboard'

If this is the error you're getting, then you need to add the following to viewDidLoad:

if let myTableView = self.tableView {
    self.tableView!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
} 

Otherwise dequeueReusableCellWithIdentifier does not know what kind of class to use for the cell.



回答2:

Could you post the error message? Also, wether the app builds or fails building is not only about the code in your .swift files, it's also about the correct tagging/identifying in your storyboard. Have you made sure you haven't messed up the cell identifiers on your project earlier?



回答3:

You may simply need to set the prototype cell identifier to "Cell". (Make sure it is exactly the same as in the code).

Go to the storyboard, click on your tableview, click on the attributes.

Give yourself a prototype cell by changing it from 0 to 1.

Click on the prototype cell. Set the 'identifier' attribute to "cell".



回答4:

I believe that you need to set the Prototype Cell to have the identifier "Cell". You do this by:

Going to Main.storyboard, clicking the cell in the Document Outline, then go to the Attributes Inspector and Type in Cell in the 'Identifier' field.