2

I am trying to programmatically add UITableViewCells in swift and getting the following error message:

2016-05-10 21:58:41.961 appname[28802:2378292] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle (loaded)' with name 'myCell''

I have the following in my viewDidLoad:

let myNib = UINib(nibName: "myCell", bundle: nil)
tableView.registerNib(myNib, forCellReuseIdentifier: "UITableViewCell")

and the following in func tableView:

 var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("UITableViewCell", forIndexPath:indexPath)

        print("setup cell")

        if cell == nil{
            print("cell == nib")
            let cellnib = [NSBundle.mainBundle().loadNibNamed("myCell", owner:self, options: nil)]
            cell = cellnib.first! as! UITableViewCell
        }
Code Different
  • 90,614
  • 16
  • 144
  • 163
pullyl
  • 126
  • 1
  • 7
  • You don't really "add" a cell to a tableview like that. Take a look here: http://stackoverflow.com/questions/3333545/how-to-display-the-uitableview-programmatically – joels May 11 '16 at 03:10

2 Answers2

2

I suggest you give the Table View Programming Guide a read. It's a long one and written in ObjC but well worth it.

For your question, you don't create a UITableViewCell like that. Try this instead:

var cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath:indexPath)

if cell == nil {
    print("setup cell")
    cell = UITableViewCell(style: .Default, reuseIdentifier: "myCell")
}
Code Different
  • 90,614
  • 16
  • 144
  • 163
  • Thanks, this is similar to what I was able to do to get it working. This tutorial proved to be very helpful - https://www.hackingwithswift.com/example-code/uikit/how-to-register-a-cell-for-uitableviewcell-reuse – pullyl May 11 '16 at 03:48
0

Actually you can create Table Cells like that but you need to put that code inside init not within the viewDidLoad:

   required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.registerNib(UINib(nibName: "myCell", bundle: nil), forCellReuseIdentifier: Identifier)
    }

But make sure myCell.xib exist in your project. To create it Right Click on the Project Directory in left and Select New File. Then Select iOS -> Source -> Cocoa Touch Class. In the class name use: myCell and Sub Class to be UITableViewCell. Checkmark also create XIB File:

Preview

Ghulam Ali
  • 1,935
  • 14
  • 15