Robert Robert - 9 months ago 52
iOS Question

Why does deleted row appear after insertion instead of the new row?

I have a custom cell with Text Field. I do row deletion in a standard manner:

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCellWithIdentifier("cellId", forIndexPath: indexPath) as! MyCell

myCell.textField.placeholder = dataArray[indexPath.row]

return myCell

Also I use my own class for the cell.

class MyCell: UITableViewCell {

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")

let textField: UITextField = {
var field = UITextField()
field.placeholder = "Placeholder Text"
field.translatesAutoresizingMaskIntoConstraints = false
return field

func setupViews() {

//Constraints stuff

The problem is if Text Field contains a text and I delete that row, after insertion of a new row I get the old one with the text.

How can I avoid it? I need clean row.

BTW, animation doesn't work properly as well.

Thank you for your help!

Answer Source

Use UITableViewCell's prepareForReuse() method.

func prepareForReuse() {
    textField.text = nil

More info here.