iOS Swift:当我滚动表格视图时,数据消失了。

4

我已经开始学习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
    }

}

请问如何正确地编写上述代码?

谢谢。

2个回答

2
问题在于每次单元格出现时您都会添加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
}

你可以尝试创建一个自定义的单元格和标签,或者检查lblPrint是否已经存在于单元格的contentView中。


1

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

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

在TableViewController类中,为表视图设置以下属性。
tableView.estimatedRowHeight = 140

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接