如何从另一个执行 class 的 collectionView 方法?

How can I execute the collectionView methods of a class from another one?

我有我的 class CardSensors,它有一个 collectionView,里面装满了另一个 XIB

class CardSensors: UIView {
    @IBOutlet weak var botName: UILabel!
    @IBOutlet weak var sensorsCollectionView: UICollectionView!
    var sensors = [[String: Any]]()

    var viewModel: NewsFeedViewModel! {
        didSet {
            setUpView()
        }
    }

    func setSensors(sensors: [[String: Any]]){
        self.sensors = sensors
    }

    static func loadFromNib() -> CardSensors {
        return Bundle.main.loadNibNamed("CardSensor", owner: nil, options: nil)?.first as! CardSensors
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    func setupCollectionView(){
        let nibName = UINib(nibName: "SensorCollectionViewCell", bundle: Bundle.main)
        sensorsCollectionView.register(nibName, forCellWithReuseIdentifier: "SensorCollectionViewCell")
    }

    func setUpView() {
        botName.text = viewModel.botName
    }

}

extension CardSensors: UICollectionViewDataSource {

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "SensorCollectionViewCell", for: indexPath) as? SensorCell else {
            return UICollectionViewCell()
        }

        cell.dateLabel.text = sensors[indexPath.row]["created_at"] as? String
        cell.sensorType.text = sensors[indexPath.row]["type"] as? String
        cell.sensorValue.text = sensors[indexPath.row]["value"] as? String
        cell.sensorImage.image = UIImage(named: (sensors[indexPath.row]["type"] as? String)!)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return sensors.count
    }

}

我正在像这样在另一个 class 中创建一个对象,但我希望它调用 collectionView 的方法来加载信息。

let sensorView = CardSensors.loadFromNib()
sensorView.sensors = sensores
sensorView.setupCollectionView()

问题是从不调用 collectionView 方法。我该怎么做才能从我的另一个 class 呼叫他们?

您需要设置数据源

 sensorsCollectionView.register(nibName, forCellWithReuseIdentifier: "SensorCollectionViewCell")
 sensorsCollectionView.dataSource = self
 sensorsCollectionView.reloadData()

然后在你的 vc 里面,让它成为一个实例变量

var sensorView:CardSensors!

sensorView = CardSensors.loadFromNib()
sensorView.sensors = sensores
sensorView.setupCollectionView()