我超级简单的 UICollectionView 没有加载

My super simple UICollectionView is not loading

我正在尝试创建一个简单的 collection 视图。我有自定义单元格“SectionCell”和自定义 class“Section”,其中包含两个 @IBOutlet 属性:titleLabel 和 imageView。这两个属性都连接到它们各自的故事板视图。

在 Storyboard 中,collectionView 场景已链接到继承自 UICollectionView 的 MenuVC.swift 文件。 Cell 视图链接到 SectionCell。我已将单元格的标识符设置为“部分”。

出于调试目的,我已将 view.backgroundColor 设置为黑色,并将单元格的 contentView 背景色设置为蓝绿色。然而,当我 运行 模拟器既不显示。我得到一个白色背景,所有出现的都是视图标题。关于修复的任何想法?

class MenuVC: UICollectionViewController {
    
    var sections = [Section]()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "Begin Learning"
        
        view.backgroundColor = .black
    }

    
    // MARK:- CollectionView Methods
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 3
    }

    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Section", for: indexPath) as? SectionCell else {
            fatalError("Unable to dequeue SectionCell ")
        }
        
        let section = sections[indexPath.item]
        cell.titleLabel.text = section.title
        cell.imageView.image = UIImage(named: section.image)

        return cell
    }
}

class SectionCell: UICollectionViewCell {
    
    @IBOutlet var imageView: UIImageView!
    @IBOutlet var titleLabel: UILabel!
    
}

class Section: NSObject {
    
    var title: String
    var image: String
    
    init(title: String, image: String) {
        self.title = title
        self.image = image
    }
}

Simulator

我对在 SO 上发帖也很陌生。如果您有任何关于如何更好地格式化问题的提示,我会洗耳恭听!

创建 collectionview 的出口并将其提供给委托和数据源...

在你的视图控制器中像这样创建插座:

@IBOutlet weak var collectionView: UICollectionview!

然后将此代码放入 viewDidLoad()

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.delegate = self
    collectionView.dataSource = self
    collectionView.relaodData()
}

你实现了以下协议吗?

UICollectionViewDelegateFlowLayout

extension MenuVC: UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: 300.0, height: 300.0) // and set size for each item inside this function.
    }
}

已解决

大声笑,作为开发人员,您确实需要敏锐的眼光。这个:

override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 3
    }

应该是:

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }

瞧!