代码之家  ›  专栏  ›  技术社区  ›  Jalil

如何从另一个类执行类的CollectionView方法?

  •  0
  • Jalil  · 技术社区  · 7 年前

    我有我的班级卡片传感器,里面有一个集合视图,里面有另一个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
        }
    
    }
    

    我在另一个类中创建了一个这样的对象,但是我希望它调用collectionview的方法来加载信息。

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

    问题是collectionview方法从未被调用。我该怎么称呼他们呢?

    1 回复  |  直到 7 年前
        1
  •  1
  •   Shehata Gamal    7 年前

    你需要设置数据源

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

    然后在vc中,将其设置为一个实例变量

    let sensorView:CardSensors!
    
    sensorView = CardSensors.loadFromNib()
    sensorView.sensors = sensores
    sensorView.setupCollectionView()
    
    推荐文章