Swift 4 中的 UICollectionViewController 未调用 cellForItemAt 函数

cellForItemAt function not getting called at UICollectionViewController in Swift 4

这看起来很基础,但我无法在 Swift 4.

中使用它

所以我有以下 UICollectionViewController 的实现

class TestController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(MyCell.self, forCellWithReuseIdentifier: "default")
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        return collectionView.dequeueReusableCell(withReuseIdentifier: "default", for: indexPath)
    }

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


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return .init(width: view.frame.width, height: 100)
    }
}

虽然 ... numberOfItems ... 方法正在被调用,但是 ... cellForItemAt indexPath ... 的方法没有被调用。

我错过了什么?

这是单元格的代码

class MyCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .green
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

此外,我没有使用故事板,所以我在 AppDelegate class:

中按如下方式实例化此控制器
...
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        window = UIWindow()
        window?.makeKeyAndVisible()

        window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))

        return true
    }
...

而不是

window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: .init()))

在 didFinishLaunchingWithOptions 方法中使用这个

 window?.rootViewController = UINavigationController(rootViewController: TestController(collectionViewLayout: UICollectionViewFlowLayout()))