等待数据传递过来再执行

Wait for data to be passed before execution

我的 tableViewCell 中有一个函数,我正在打印数据计数。但是当我查看日志时:

Table View Cell TRAINING COUNT is 0
Table View TRAINING COUNT is 3
Table View Cell TRAINING COUNT is 0
Table View TRAINING COUNT is 4
Table View Cell TRAINING COUNT is 0
Table View TRAINING COUNT is 1

tableViewCell 上的打印:

import UIKit

class HomeTableViewCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    @IBOutlet weak var collectionView: UICollectionView!
    var trainings = [Training]()
    var trainingCategories = [TrainingCategory]()

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
        print("Table View Cell TRAINING COUNT is \(trainings.count)")
    }
}

在tableViewController的每一行打印前先执行:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TrainingTableCell", for: indexPath) as! HomeTableViewCell
    var trainingsUnderCategory = [Training]()
    for counter in 0 ..< trainings.count{
        if trainingCategories[indexPath.section].id! == trainings[counter].category_id!{
            trainingsUnderCategory.append(trainings[counter])
        }
    }
    cell.backgroundColor = .white
    cell.trainings = trainingsUnderCategory
    print("Table View TRAINING COUNT is \(cell.trainings .count)")
    return cell
}

我看不出如何在这里使用闭包,或者我错了吗?感谢任何愿意回答的人!

当您通过 dequeueReusableCell 函数调用创建单元格时,将调用

awakeFromNib。一切正常。如果您想使用给定的 trainings 数据配置 HomeTableViewCell,您可以通过创建一个函数来实现。这是一个例子:

// cellForRowAt
...
cell.setTrainings(trainings)
return cell

// HomeTableViewCell
...
func setTrainings(_ trainings: [Training]) {
    self.trainings = trainings
    // Do configuration here

}

您不一定需要在单元格中创建函数,您也可以在 cellForRowAt 函数中进行配置,但分离配置在代码方面会更好。