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

后端 未结 7 2174
不思量自难忘°
不思量自难忘° 2020-11-27 05:25

I added UICollectionView by code.
Now, the app crash with message: UICollectionView must be initialized with a non-nil layout parameter.
Do

相关标签:
7条回答
  • 2020-11-27 06:29

    Swift 5 general solution

    Can use UICollectionViewDelegateFlowLayout and don't forget to set your cell size

    class YourViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize.init(width: view.frame.width, height: 250)
        }
        override func viewDidLoad() {
            super.viewDidLoad()
            self.collectionView!.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        }
        // initialized with a non-nil layout parameter
        init() {
            super.init(collectionViewLayout: UICollectionViewFlowLayout())
        }    
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
    0 讨论(0)
提交回复
热议问题