Search code examples
iosuitableviewios9xcode7nib

registerNib UiTableView not working after project corruption


I am new to iOS. I have a cellForRowIndexPath implementation as follows

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("ListCell")
    if cell == nil {
        let bundle = NSBundle(forClass: self.dynamicType)
        tableView.registerNib(UINib(nibName: "Cell",bundle : nil), forCellReuseIdentifier : "ListCell")
        cell = tableView.dequeueReusableCellWithIdentifier("ListCell")
    }
    (cell as? Cell)?.label.text = data[indexPath.row].name
    return cell!
 }

This code was working initially. I accidentally did a git hard reset. The project files got all messed up. I fixed the other issues. In some cases by adding the files back again. But for some reason this piece of code is not working now. There is Cell.xib file in the project

The error is 'Use of undeclared type Cell' at

(cell as? Cell)?.label.text = data[indexPath.row].name

How do I fix this?

Thanks in advance!


Solution

  • First, you only need to register nib one time, so put this code in your viewDidLoad or tableView's didSet:

    tableView.registerNib(UINib(nibName: "Cell",bundle : nil), forCellReuseIdentifier : "ListCell")
    

    In your cellForRow, change your code to:

    var cell: Cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as! Cell
    cell.label.text = data[indexPath.row].name
    return cell
    

    You got error because you dont cast the default UITableViewCell to your custom Cell