Xcode初学者在简单的tableview代码上有运行时错误

时间:2015-02-17 23:47:20

标签: xcode uitableview swift

我正在学习如何使用Simon NG Swift编程指南使用基于表格的应用程序。我逐字输入代码,Xcode环境卡在let cell = tableView代码行上。

有人能告诉我我做错了吗?

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


}

4 个答案:

答案 0 :(得分:3)

运行代码时遇到的第一个错误是:

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'

如果这是你得到的错误,那么你需要将以下内容添加到viewDidLoad:

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

否则dequeueReusableCellWithIdentifier不知道要为单元格使用哪种类。

答案 1 :(得分:0)

您可以发布错误消息吗? 此外,应用程序构建或构建失败不仅仅是关于.swift文件中的代码,还涉及故事板中正确的标记/识别。您是否确定早些时候没有弄乱项目中的单元格标识符?

答案 2 :(得分:0)

您可能只需要将原型单元标识符设置为" Cell"。 (确保它与代码中的完全相同)。

转到故事板,点击你的桌面视图,点击属性。

通过将原型单元格从0更改为1来为自己提供原型单元格。

单击原型单元格。设置'标识符'属性为" cell"。

答案 3 :(得分:0)

我认为您需要将Prototype Cell设置为具有标识符" Cell"。你这样做:

转到Main.storyboard,单击文档大纲中的单元格,然后转到属性检查器并在标识符'中键入单元格。字段。

相关问题