Adnan Momin Adnan Momin - 1 year ago 68
iOS Question

UITableViewCell Data changes after scrolling

I am creating a form in UITableViewCell, this form has lable and text field, in prototype cell. See its image here
TableView Story board Image.
I am using identifier to dynamically create the form, my code is

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

let cell = tableView.dequeueReusableCellWithIdentifier("protocell", forIndexPath: indexPath) as! UITableViewCell

var lable = cell.viewWithTag(1) as! UILabel
lable.text = details[indexPath.row]
lable.textColor = UIColor.brownColor().colorWithAlphaComponent(0.7)

var textfield = cell.viewWithTag(2) as! UITextField
textfield.placeholder = "Enter \(details[indexPath.row])"
if details[indexPath.row] == "Name" {
textfield.placeholder = "Enter First \(details[indexPath.row]) Middle \(details[indexPath.row]) Last \(details[indexPath.row]) "
textfield.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.2)

return cell

Now the problem is I am having 18 fields and when I enter values in the field and scroll the the view to fill the remaining fields, the values changes in the fields changes.
Please help.

Answer Source

Create UITableViewCell subclass and override prepeareForReuse function - to turn cell to default mode.


override func prepareForReuse() {

    //set cell to initial state here, reset or set values, etc.

As per your comment - of how to subclass UITableViewCell:

import UIKit

class MyCustomCell: UITableViewCell {
     // things that you can do here:
     // initialise your properties here. (label, textfield. etc)
     // layout subviews.
     // override superclass APIs.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download