You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5中UICollectionView已创建Cell但无法显示的问题求助

UICollectionViewCell 无法显示问题排查与解决

我在Storyboard中创建了UICollectionView,使用自定义UICollectionViewCell构建集合视图,但遇到了cell完全无法显示的问题——不管用自定义Cell还是默认Cell都看不到内容,试过各种方案都没解决,求帮忙。


视图控制器代码

viewDidLoad 方法

override func viewDidLoad() {
    super.viewDidLoad()
    
    collectionView.delegate = self
    collectionView.dataSource = self
    
    title = set?.name
    
    collectionView!.register(WordCollectionViewCell.self, forCellWithReuseIdentifier: Identifies.WordCollectionViewCellIdentifier)
    
    let buttonItem  = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonPressed))
    
    navigationItem.rightBarButtonItem = buttonItem
    updateTranslations()
}

UICollectionView 代理与数据源扩展

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

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Identifies.WordCollectionViewCellIdentifier, for: indexPath) as! WordCollectionViewCell
        
        cell.translation = translations[indexPath.row]
    
        return cell
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1 
    }
}

自定义UICollectionViewCell代码

class WordCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var wordLabel: UILabel!
    
    private var showsWord = true
    
    private var _translation : Translation?
    var translation : Translation  {
        set {
            _translation = newValue
        }
        get {
            return _translation ?? Translation(word: "", translation: "")
        }
    }
    override func awakeFromNib() {
        super.awakeFromNib()
        
        let gestureRecognizer = UITapGestureRecognizer(target: self , action: #selector(flip))
        gestureRecognizer.numberOfTapsRequired = 1
        self.addGestureRecognizer(gestureRecognizer)
        
        wordLabel.text = _translation?.word
    }
    
    @objc private func flip(_ sender: UIGestureRecognizer){
        let options : UIView.AnimationOptions = [.transitionFlipFromRight]
        UIView.transition(with: self, duration: 0.5, options: options){
            if let translation = self._translation {
                    self.wordLabel.text = self.showsWord ? translation.translation : translation.word
                    self.showsWord = !self.showsWord
            }
        }
    }
    
    static func nib() -> UINib {
        return UINib(nibName: NibNames.WordCollectionViewCellNibName, bundle: nil)
    }
}

排查与解决步骤

  1. 修正Cell注册方式
    你现在用register(WordCollectionViewCell.self, ...)注册Cell,但自定义Cell是基于XIB创建的,这种方式不会加载XIB布局,导致Cell没有尺寸和内容。替换成XIB注册方式:

    collectionView!.register(WordCollectionViewCell.nib(), forCellWithReuseIdentifier: Identifies.WordCollectionViewCellIdentifier)
    
  2. 同步更新Label内容
    当前设置cell.translation时,仅赋值了_translation,没有更新wordLabel。awakeFromNib只会在Cell初始化时调用一次,后续赋值不会触发文本更新。修改translation的setter:

    var translation : Translation  {
        set {
            _translation = newValue
            wordLabel.text = newValue.word // 实时更新Label
            showsWord = true // 重置显示状态
        }
        get {
            return _translation ?? Translation(word: "", translation: "")
        }
    }
    

    同时删掉awakeFromNib中的wordLabel.text = _translation?.word——此时_translation还未赋值,只会让Label初始为空。

  3. 检查CollectionView布局

    • 确保Storyboard中UICollectionView的约束正确(比如上下左右绑定父视图,避免尺寸为0)。
    • 检查FlowLayout的itemSize是否合理,若设置为(0,0)也会导致Cell不可见。可以在viewDidLoad中添加:
      if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
          layout.itemSize = CGSize(width: 150, height: 80) // 根据需求调整尺寸
          layout.minimumInteritemSpacing = 10
          layout.minimumLineSpacing = 10
      }
      
  4. 确认数据加载与刷新
    确保updateTranslations()执行后,translations数组被正确填充,且异步加载数据后要调用collectionView.reloadData():

    func updateTranslations() {
        // 假设是异步加载逻辑
        DispatchQueue.main.async {
            self.translations = // 加载到的数据源
            self.collectionView.reloadData()
        }
    }
    

内容的提问来源于stack exchange,提问作者Leonid06

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 10:20:17