在iOS 8.3上注册Nib / Class单元格崩溃

时间:2016-09-27 11:29:33

标签: ios swift uitableview ios8.3

我在viewDidLoad中使用了以下代码来注册nib cell:

tableView.register(UINib(nibName: "ShoppingViewCell", bundle: Bundle.main), forCellReuseIdentifier: "ShoppingViewCell")

cellForRowAtIndexPath中,我将以下内容用于单元格:

let cell = self.tableView.dequeueReusableCell(withIdentifier: "ShoppingViewCell", for: indexPath) as! ShoppingViewCell

return cell

但遗憾的是,这仅适用于IOS 9及更高版本,尝试在iOS 8.3上运行此代码时出现以下错误:

2016-09-27 14:17:04.859 Tazaj[29070:1917376] *** Assertion failure in -[UITableView dequeueReusableCellWithIdentifier:forIndexPath:], /SourceCache/UIKit_Sim/UIKit-3347.44/UITableView.m:6245
2016-09-27 14:17:04.877 Tazaj[29070:1917376] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier ShoppingViewCell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard'

由于自iOS 5/6以来已经找到了注册nib和dequeueReusableCell,为什么它不适用于iOS 8.3。

我知道通过在cellForRowAtIndex中运行以下代码可以解决问题:

    var mycell = tableView.dequeueReusableCell(withIdentifier: "ShoppingViewCell") as? ShoppingViewCell

    if (mycell == nil) {

        mycell = Bundle.main.loadNibNamed("ShoppingViewCell", owner: nil, options: nil)?.last as? ShoppingViewCell

    }

但我已经建立了整个项目而没有检查单元格是否为零。我的意思是我该如何解决这个问题?因为苹果说注册细胞并按照你想要的方式使用细胞,我做到了。那么为什么只有在iOS 8.x / 8.3中它才能起作用?

如何在每个cellForRowAtIndexPath中最少替换代码块来忽略/修复该错误?

1 个答案:

答案 0 :(得分:1)

只需将此方法放入自定义单元格类

即可
class func cellForTableView(tableView: UITableView, atIndexPath indexPath: NSIndexPath) -> ShoppingViewCell {
    let kShoppingViewCellIdentifier = "kShoppingViewCellIdentifier"
    tableView.registerNib(UINib(nibName: "ShoppingViewCell", bundle: NSBundle.mainBundle()), forCellReuseIdentifier: kShoppingViewCellIdentifier)
    let cell = tableView.dequeueReusableCellWithIdentifier(kShoppingViewCellIdentifier, forIndexPath: indexPath) as! ShoppingViewCell
    return cell
}

并在cellForRowAtIndexPath

中使用它
let cell = ShoppingViewCell.cellForTableView(tableView, atIndexPath: indexPath)
// do something with your cell

我希望它有所帮助。

更新Swift 3和Swift 4

class func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> YourCustomTableViewCell {
    let kYourCustomTableViewCellIdentifier = "kYourCustomTableViewCellIdentifier"
    tableView.register(UINib(nibName: "YourCustomTableViewCell", bundle: Bundle.main), forCellReuseIdentifier: kYourCustomTableViewCellIdentifier)
    let cell = tableView.dequeueReusableCell(withIdentifier: kYourCustomTableViewCellIdentifier, for: indexPath) as! YourCustomTableViewCell
    return cell
}