iOS Swift:当我滚动Tableview数据时会消失

我已经开始Swift编程,并且对tableview控件有点混淆。 为了实现我写下面的代码,但数据将消失,当我滚动它。

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 } } 

上面的代码写的是正确的方法是什么?

谢谢

问题是你正在添加var lblPrint : UILabel! 每当细胞出现时。

您可以使用UITableViewCell.textLabel代替添加自定义标签字段。

例如:

 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 } 

您也可以尝试使用自定义标签创build自定义单元格,或者您应该检查单元格的contentViewlblPrint已经存在lblPrint

对我来说,这个问题是通过覆盖下面的方法来解决的。 我刚从方法返回UITableViewAutomaticDimension

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } 

并为TableViewController类中的表视图设置以下属性。

 tableView.estimatedRowHeight = 140