首页 > 解决方案 > 加载 UICollectionViewCell 时,IBOutelt 发现 nil

问题描述

我正在研究如何在没有情节提要的情况下创建一个简单的应用程序,但我遇到了一个问题:我创建了一个名为 的 XIB HomeViewController,其中有一个UICollectioView并在viewDidLoad(). 之后,我创建了一个名为 的单元格HomeCollectionViewCell,将其identifier作为“单元格”,在它有一个UILabel插座的单元格中,它在 .swift 文件中被引用。在设置delegate和之后datasource,它具有数据源的强制方法,在进行单元格配置和通过设置返回 nil 的任何文本调用标签时。我不知道为什么会这样,我在 YouTube 上看过几个视频,但都没有解决问题。有谁能够帮我?

主视图控制器

class HomeViewController: UIViewController {

   @IBOutlet weak var collectionView: UICollectionView!

   var info = ["Image"]

   override func viewDidLoad() {
       super.viewDidLoad()
       collectionView.register(HomeCollectionViewCell.self, forCellWithReuseIdentifier: 
                               "cell")
       collectionView.delegate = self
       collectionView.dataSource = self
    }
  }

  extension HomeViewController: UICollectionViewDelegate, UICollectionViewDataSource {
      func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection 
                          section: Int) -> Int {
       
       return info.count
  }

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: 
                      IndexPath) -> UICollectionViewCell {

       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: 
                                                     indexPath) as? HomeCollectionViewCell
       cell?.teste.text = "test"
       return cell!
    
  }


 }

主页集合查看单元格

class HomeCollectionViewCell: UICollectionViewCell {

   @IBOutlet weak var teste: UILabel!

   override func awakeFromNib() {
       super.awakeFromNib()
     
   }

 }

标签: iosswift

解决方案


那是因为您必须注册单元格的笔尖而不仅仅是类:

collectionView.register(UINib(nibName: "HomeCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell")

推荐阅读