如何在没有原型单元的情况下创建tableview

时间:2015-04-10 16:38:58

标签: uitableview swift

如果我不想在我的tableview中使用原型单元格。在cellForRowAtIndexPath中,我是否仍需要在代码中提供单元格标识符以使单元格出列?

我试过这个但是当tableview尝试填充时会抛出运行时错误:

  

致命错误:在解包可选值时意外发现nil

它发生在这一行:

let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell 

我不确定将哪一行用于出列单元格。

2 个答案:

答案 0 :(得分:3)

是的,你必须或者swift没有办法找出你想要dequeue的对象,因此你得到了nil个对象。

你应该使用  - dequeueReusableCellWithIdentifier:forIndexPath:

而不是 - dequeueReusableCellWithIdentifier

这是因为第一个实际返回AnyObjectdequeue没有indexpath返回AnyObject?

为了使您的代码有效,您可以将代码更改为...forIndexPath

或者这样做:

var cell: UITableViewCell?
if let cell = cell {
    //dequeue here
} else {
    cell = UITableViewCell(style: UITableViewCellStyle,
reuseIdentifier reuseIdentifier: String?) ...
}
//config cell
return cell

如果你是一个做所有事情的人,你需要像Mert建议的那样将你的UITableViewCell课程注册到tableView

tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier identifier: "Cell")


示例代码:

// I remove all other things, just focus on what you need
override func viewDidLoad() {
        super.viewDidLoad()
        table.delegate = self
        table.dataSource = self
        table.registerClass(UITableViewCell.self, forCellReuseIdentifier identifier: "Cell")
    }

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        configureCell(cell, atIndexPath: indexPath)
        return cell
    }

答案 1 :(得分:0)

您需要为该单元格类创建表视图注册

tableView.registerClass(_ cellClass: AnyClass, forCellReuseIdentifier identifier: String)

,然后您可以尝试将单元格出列。如果没有单元格出列,则需要创建一个新单元格。

但您的主要问题应该是:dequeueReusableCellWithIdentifier返回optional。如果你想把它作为单元格返回,它可能会给出错误。您应该确保在non-optional函数中返回cellForRowAtIndexPath单元格。