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

Nicolas Meienberger picture Nicolas Meienberger · May 21, 2015 · Viewed 9.6k times · Source

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

Answer

Adam Bardon picture Adam Bardon · May 21, 2015

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