我有我的CardSensors类,该类具有一个用另一个XIB填充的collectionView
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方法永远不会被调用。我该怎么做才能从其他班级给他们打电话?
答案 0 :(得分:1)
您需要设置数据源
sensorsCollectionView.register(nibName, forCellWithReuseIdentifier: "SensorCollectionViewCell")
sensorsCollectionView.dataSource = self
sensorsCollectionView.reloadData()
然后在vc中,使其成为实例变量
var sensorView:CardSensors!
sensorView = CardSensors.loadFromNib()
sensorView.sensors = sensores
sensorView.setupCollectionView()