Reputation: 126
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
}
Upvotes: 2
Views: 380
Reputation: 1935
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:
Upvotes: 0
Reputation: 93151
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")
}
Upvotes: 2