collectionView:layout:sizeForItemAt 未调用 swift 4 iOS 11

collectionView:layout:sizeForItemAt not called swift 4 iOS 11

class HomeController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    private let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.register(Cell.self, forCellWithReuseIdentifier: cellId)
        collectionView?.backgroundColor = UIColor.red
    }

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

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

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath) as! Cell
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 150, height: 150)
    }
}

class Cell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)

        setup()
    }

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

    func setup() {
        backgroundColor = UIColor.black
    }
}

numberOfSectionsnumberOfItemsInSection 被调用(根据断点),但 cellForItemAtsizeForItemAt 从未被调用。

我看不出有什么不对吗?

更新:(我如何在 AppDelegate 中创建 HomeController)

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    window = UIWindow(frame: UIScreen.main.bounds)
    window?.makeKeyAndVisible()

    let layout = UICollectionViewLayout()
    let homeController = HomeController(collectionViewLayout: layout)
    window?.rootViewController = UINavigationController(rootViewController: homeController)

    return true
}

您正在使用 UICollectionViewLayout()

你应该use -

 let layout = UICollectionViewFlowLayout()