即使在ViewDidLoad中初始化之后,UICollectionView也必须用一个非nil布局参数初始化



我试着做所有其他问题似乎做的事情,但我仍然得到错误。也许我错过了一些明显的东西,但我看了文档,似乎只是你需要一个布局来初始化。

let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView?.delegate = self
collectionView?.dataSource = self
collectionView?.register(InterestCollectionViewCell.self, forCellWithReuseIdentifier: interestReuseIdentifier)
view.addSubview(collectionView!)

集合视图委托方法

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return interests.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let vc = collectionView.dequeueReusableCell(withReuseIdentifier: interestReuseIdentifier, for: indexPath) as! InterestCollectionViewCell
    vc.interestLabel.text = interests[indexPath.row].rawValue as String
    return vc
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.size.width, height: 45)
}

解决方案是,我必须在呈现UICollectionViewController之前初始化collectionView。我必须在viewWillAppear中注册单元格类而不是viewDidLoad

最新更新