Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Impossible to use "registerNib" on my tableView to add a custom cell

I'm just figuring out how to add custom cells to a tableView in Swift. I watched a lot of tutorials and they all say at some point to use something like tableView.registerNib which is not working for me !

This is the code I'm using in my tableViewController class :

var nib = UINib(nibName: "ViewExerciceCell", bundle: nil)
tableView.registerNib(nib, forCellReuseIdentifier: "ExerciceCell")

When I try to build, I have an error on the second line which says :

Cannot invoke 'registerNib' with an argument list of type '(UINib, forCellReuseIdentifier: String)'.

What can I do ? All the tutorials and other answers about custom cells are using this code.

Thanks in advance

like image 278
Nicolas Meienberger Avatar asked May 21 '15 08:05

Nicolas Meienberger


3 Answers

I'm using following code inside tableView:cellForRowAtIndexPath function:

var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as UITableViewCell
if cell == nil {
    tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
    cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as UITableViewCell!
}

return cell

If you have your custom cell in storyboard or .xib file, don't forget to set Identifier(in this case CustomCell) in Attributes inspector

like image 83
Adam Bardon Avatar answered Nov 09 '22 09:11

Adam Bardon


After some head-banging I realized my error:

Instead of "forCellReuseIdentifier" I was supposed to use forCellWithReuseIdentifier. With so many things changing with Swift so swiftly, Its hard to keep up with all the changes. Hope this helps.

Solution that worked for me:

self.collectionView!.register(UINib(nibName: "CategoryCVCell", bundle: nil), forCellWithReuseIdentifier: "CategoryCVCell")
like image 3
Obj-Swift Avatar answered Nov 09 '22 09:11

Obj-Swift


Ok... I don't know what was the problem, but removing the file reference of my cell.xib in my project and adding it again just solved the problem. I already had some problems resolved like that in the past.

Thank you all for your quick answers !

like image 2
Nicolas Meienberger Avatar answered Nov 09 '22 08:11

Nicolas Meienberger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!