【问题标题】:Wrong population of Table View表格视图的错误填充
【发布时间】:2020-03-03 17:40:13
【问题描述】:

你好!问题是我无法用数据填充我的表格视图。尽管在某种程度上它是正确的,但我意识到程序一次又一次地将一个视图置于另一个视图之上。下面,我提供了与问题绝对相关的代码片段

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if cell.isHidden == true {

            cell.isHidden.toggle()

        }
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let record = records[indexPath.section][indexPath.row]

        let view = RecordView(price: record.price, place: record.place, time: record.date?.getDay(), category: record.category)

        let cell = tableView.dequeueReusableCell(withIdentifier: "RecordViewCell", for: indexPath) as! RecordViewCell

        cell.setRecordView(record: view)



        cell.clipsToBounds = true
        cell.contentView.backgroundColor = UIColor.clear
        cell.layer.backgroundColor = UIColor.clear.cgColor
        cell.backgroundColor = .clear

        return cell



    }

还有,

class RecordViewCell: UITableViewCell {

    @IBOutlet weak var view: UIView!

    func setRecordView(record: RecordView) {

        view.addSubview(record)
        record.frame = CGRect(x: 5, y: 5, width: view.frame.width - 10, height: 60)

    }

    override func prepareForReuse() {
        super.prepareForReuse()
        self.isHidden = true
    }



}

This is the link to the pic of how the table looks in general. There you can see that the shadows are overlapped and wrong.

非常感谢您。

【问题讨论】:

  • 图片到底有什么问题?我不确定预期的行为是什么。 isHidden 的魔法可能根本不需要。

标签: ios swift uitableview swift5


【解决方案1】:

整个RecordView 应该由表创建。每次重用单元格时都会创建一个新视图,这一事实使得无法重用视图,这就是重用单元格的全部意义所在。

但是,作为一种快速修复,您必须始终删除以前的视图:

@IBOutlet weak var view: UIView!

var record: RecordView? {
   didSet {
      oldValue?.removeFromSuperview()

      guard let record = record else { return } 

      view.addSubview(record)
      record.frame = CGRect(x: 5, y: 5, width: view.frame.width - 10, height: 60)
   }
}

【讨论】:

    【解决方案2】:

    由于单元格重用,当您将子视图添加到单元格时,这不是每次都是新单元格,有时它会重用一个。 在这种情况下,最好将记录视图作为单元格属性并将新记录分配给该属性。在这种情况下,您将在此处避免使用多个子视图。 另外,我实际上不明白为什么您将单元格隐藏在 prepareForReuse 中,这是一种奇怪且不必要的行为。

    class RecordViewCell: UITableViewCell {
    
        @IBOutlet weak var recordView: RecordView!
    
        func setRecordView(record: RecordView) {
    
            recordView = record
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-12
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多