Rawan Rawan - 4 months ago 90x
Swift Question

How to prevent UITableView from reuse custom cells Swift

In my App I use UITableView with custom cells.

for each cell I implement function to create it, and call these functions in cellForRow.

this is an code example from project :

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if indexPath.row == CellsTypes.profileImageCell.rawValue {

return createIntroCell()

else if indexPath.row == CellsTypes.fullNameCell.rawValue {

return createUserNameCell()


else if indexPath.row == CellsTypes.emailCell.rawValue {

return createEmailCell()

else {

return createPasswordCell()


and these are the creation functions :

func createUserNameCell() -> TextFieldTableViewCell {

let fullNameCell = self.tableView.dequeueReusableCellWithIdentifier("text-field-cell") as! TextFieldTableViewCell
fullNameCell.awamirTextFieldNib.setNormalTextFieldCellContent("Full Name")
fullNameCell.awamirTextFieldNib.textFieldContent.tag = CellsTypes.fullNameCell.rawValue
fullNameCell.awamirTextFieldNib.textFieldContent.returnKeyType = .Next
fullNameCell.awamirTextFieldNib.textFieldContent.delegate = self
return fullNameCell

func createEmailCell() -> TextFieldTableViewCell {

let emailCell = self.tableView.dequeueReusableCellWithIdentifier("text-field-cell") as! TextFieldTableViewCell
emailCell.awamirTextFieldNib.textFieldContent.tag = CellsTypes.emailCell.rawValue
emailCell.awamirTextFieldNib.textFieldContent.returnKeyType = .Next
emailCell.awamirTextFieldNib.textFieldContent.delegate = self
return emailCell
func createPasswordCell() -> TextFieldTableViewCell {

let textFieldCell = self.tableView.dequeueReusableCellWithIdentifier("text-field-cell") as! TextFieldTableViewCell
textFieldCell.awamirTextFieldNib.textFieldContent.tag = CellsTypes.passwordCell.rawValue
textFieldCell.awamirTextFieldNib.textFieldContent.returnKeyType = .Next
textFieldCell.awamirTextFieldNib.textFieldContent.delegate = self

return textFieldCell

the problem is if I reload the tableview the content of cells changed because of the reusablity of the cells. i.e: after reload the tableview the content of the first cell become in the second cell, and the content of the sencond on became in the first cell!!

how can I prevent tableview from reusable the cells?!



Try using a different identifier for each of the cell types, so dont use "text-field-cell" for each one, make one "full name", "password" etc. not sure how you are going about creating your cells, but if you are using the registerNib or registerClass, you will need to register it for each different identifier

self.tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "full name")
self.tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "password")
self.tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "email")