ios - 即使提供布局后,UICollectionViewDelegateFlowLayout 也会出错

标签 ios swift

看到以下异常

'UICollectionView must be initialized with a non-nil layout parameter'

使用这个 ViewController

import UIKit

class SelectDesignController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    private let designCellId = "designCellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        configureNavBar()
        configureUI()
        collectionView.backgroundColor = #colorLiteral(red: 0.8515156507, green: 0.9521961808, blue: 0.9503603578, alpha: 1)
        collectionView.register(DesignCategoryCell.self, forCellWithReuseIdentifier: designCellId)
    }
    @objc func handleDismiss() {
        dismiss(animated: true, completion: nil)
    }

    func configureNavBar() {
        navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage.fontAwesomeIcon(name: .chevronLeft, style: .solid, textColor: .white, size: CGSize(width: 40, height: 40)).withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(handleDismiss))
    }
    func configureUI (){
        view.backgroundColor = #colorLiteral(red: 0.8515156507, green: 0.9521961808, blue: 0.9503603578, alpha: 1)
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: designCellId, for: indexPath) as! DesignCategoryCell
        return cell
    }
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 1
    }
    /** PROVIDING a LAYOUT HERE **/
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width, height: view.frame.height)
    }

}

我包括 SelectDesignController 如下:

let controller = SelectDesignController()
let nav = UINavigationController(rootViewController: controller)
configureNav(nav: nav, title: "Designs")
present(nav, animated: true, completion: nil)

知道吗,我错过了什么?

最佳答案

您应该检查两件事:

框架

Collection View 的框架矩形,以磅为单位。框架的原点与您计划添加它的 super View 相关。该帧在初始化期间传递给父类(super class)。

布局

用于组织项目的布局对象。 Collection View 存储对指定对象的强引用。不能为零。

关于ios - 即使提供布局后,UICollectionViewDelegateFlowLayout 也会出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58178907/

相关文章:

objective-c - 用于核心数据操作的 NSOperation

ios - 选中时展开 tableviewcell,取消选中时展开 tableviewcell Swift 3

ios - 如何在 swift iOS 中清除惰性变量的值?

ios - UIBarButtonItem 色调颜色 iOS4

ios - 如何隐藏 Storyboard中的图像/标签以在我们运行应用程序时显示?

ios - 隐藏嵌套 UISplitViewControlles 细节的主控

ios - (Swift 3)我需要向用户发送通知以在特定时间打开应用程序。使用本地通知还是推送通知更好?

ios - 如何使用 Facebook API 选择好友 ID?

ios - AVMutableComposition插入时间范围: uses wrong range

ios - UITextView 不会设置文本