Pankti Patel Pankti Patel - 4 months ago 168
iOS Question

iOS Swift : Tableview data disappear when i scroll it

I have started Swift programming and little confuse about the tableview Control. For implementation i write following code, but the data goes disappear when i scroll it.

import UIKit

class ViewController: UIViewController {

@IBOutlet var tblView: UITableView

var Array = ["1","2","3","4","5"]

override func viewDidLoad() {
super.viewDidLoad()

tblView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}


@IBAction func moveToNextView(sender: AnyObject) {

var objNextViewController : NextViewController = NextViewController(nibName: "NextViewController", bundle: nil)
self.navigationController.pushViewController(objNextViewController, animated: true)

}

func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return Array.count
}

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

//var cell : UITableViewCell! = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

var cell:UITableViewCell = tblView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var lblPrint : UILabel! = UILabel(frame: CGRectMake(10, 10, 100, 100))
lblPrint.text = Array[indexPath.row]
cell.contentView.addSubview(lblPrint)

return cell
}

}


what could be the right method to write for the above code?

Thanks

Answer

The problem is that you are adding var lblPrint : UILabel! each time when the cell appears.

Instead of adding custom label field, you can use UITableViewCell.textLabel.

For example:

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

    //var cell : UITableViewCell! = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "cell")

    var cell:UITableViewCell = tblView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    cell.textLabel = Array[indexPath.row]
    return cell
}

Also you can try to create a custom cell with a custom label or you should check if the lblPrint already exists within contentView of cell.