为什么我的 Collection View Cells 不显示在 iPhone 模拟器中?

Why won't my Collection View Cells display in the iPhone Simulator?

我正在尝试以编程方式创建一个包含六个单元格的集合视图。 iPhone Simulator in Xcode 8 告诉我构建成功。 还是有错误。

对于发现导致我的单元格无法在模拟器中显示的一个或多个错误的任何帮助,我们将不胜感激。 (我将 Collection View 从 Object Library 直接放入 IB。此外,我希望每个单元格都占据 Collection View 的整个大小,因此 displayedCellDimensions,因为用户会在向前或向后时在单元格之间切换按钮被点击。)谢谢!

import UIKit

class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {



//MARK: - Collection View Properties
@IBOutlet weak var ibCollectionView: UICollectionView!

var cellArray:[customCollectionViewCell] = Array(repeating: customCollectionViewCell(), count: 6)

let displayedCellDimensions = CGSize(width: 343, height: 248)



//MARK: - Xcode-generated Methods
override func viewDidLoad() {
    super.viewDidLoad()


    // Do any additional setup after loading the view.
    ibCollectionView.dataSource = self
    ibCollectionView.delegate = self


}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//MARK: - Collection View Methods
//Place cells in collection view and change the cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    if collectionView.visibleCells.isEmpty {
        for cell in 0...cellArray.count {
            collectionView.addSubview(cellArray[cell])
            return CGSize(width: 343, height: 248)
        }
    }
    return CGSize(width: 343, height: 248)
}

//Register a new cell
func registerCell(_ collectionView: UICollectionView) {
    for _ in 0...cellArray.count {
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
    }
}



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

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
    return cell
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    return cellArray.count


}
...}

在你的 viewDidLoad() 中尝试:

viewDidLoad() {
ibCollectionView.dataSource = self
ibCollectionView.delegate = self
}

将此添加到您 class 的顶部:

class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

您必须在 ViewController class:

中使用这些函数
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {}