使用自定义 class 设置 UICollectionView 数据源和委托时出现错误消息

Error message when setting UICollectionView data source and delegate with custom class

我正在创建一种手动幻灯片放映(即,当用户点击前进或后退按钮时图片移动),它是使用 Collection View 制作的。我不得不创建一个自定义集合单元格视图 class,我已完成,但现在我在 iOS 模拟器中收到一条错误消息,"fatal error: unexpectedly found nil while unwrapping an Optional value" 即使我的代码构建成功。错误在 ibCollectionView.dataSource = self 行,因为我是 Swift 和 OOP 的新手(大约一个月前第一次学习),我对这个错误信息感到困惑,特别是因为那里没有 ? 运算符。我在下面包含了我的代码的问题部分(显示错误消息的 Xcode 部分)。谢谢!

import UIKit

class FluidIntakeMainMenuViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

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


var cellArray:[customCollectionViewCell] = Array(repeatElement(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


}
//My code for this class continues down here...

First and most important thing is to check the IBOutlet connection that you made in your storyboard.

尝试删除情节提要中的连接,然后重新连接。

其次打开调试器检查它是否仍然为零。

 ibCollectionView.dataSource = self

我想你忘了这个:

override func viewDidLoad() {
        super.viewDidLoad()
        // Register cell classes
        ibCollectionView?.register(YourCustomCell.self, forCellWithReuseIdentifier: "Cell")

并在 cellForItemAt 中使用 "Cell" 标识符...