I am having trouble casting my table view cell to my custom table view cell in the dequeueReusableCell(withIdentifier: for:)
step.
My code:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldcell", for: indexPath) as! TextFieldTableViewCell
cell.labelTitle.text = array[indexPath.row]
return cell
}
I have registered my cell in viewDidLoad()
:
tableView.register(TextFieldTableViewCell.self, forCellReuseIdentifier: "TextFieldcell")
And I got an error saying:
fatal error: unexpectedly found nil while unwrapping an Optional value
I bet it failed the casting and that is why the cell is empty. Can anybody see the error?
Thanks!
UPDATED CODE
override func viewDidLoad() {
super.viewDidLoad()
let bundle = Bundle(for: TextFieldTableViewCell.self)
let nib = UINib(nibName: "MyTableViewCell", bundle: bundle)
tableView.register(nib, forCellReuseIdentifier: "TextFieldcell")
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TextFieldcell", for: indexPath) as! TextFieldTableViewCell
cell.labelTitle.text = array[indexPath.row]
return cell
}
}
So apparently the issue still persists, to clarify, here are the steps I took to create this custom UITableViewCell
- Create a .swift file and a .xib file
- inside of the .xib file, I have deleted the boilerplate code and added in two UILabels
- I set the file owner of the .xib file to my swift, which has my two IBOutlets
- Next, inside of my tableViewController where I want to instantiate my custom tableViewCell, inside the
viewDidLoad()
method, I added in the following:
let bundle = Bundle(for: TextFieldTableViewCell.self)
let nib = UINib(nibName: "MyTableViewCell", bundle: bundle)
tableView.register(nib, forCellReuseIdentifier: "TextFieldcell")
My reasoning for creating this code are as follow: since I have create my custom table view cell using a .xib file and interface builder, I need to load the xib into my tableViewController (correct me if I am wrong) using tableView.register(nibName: forCellReuseIdentifier:)
function.
However, when I run the code, I got an error saying: reason: 'Could not load NIB in bundle: 'NSBundle
Here is my code for my custom cell:
class TextFieldTableViewCell: UITableViewCell {
@IBOutlet weak var labelTitle: UILabel!
@IBOutlet weak var userInput: UITextField!
}
Can anybody see where the problem is? thanks!