【问题标题】:UICollectionView must be initialized with a non-nil layout parameter even after initialized in ViewDidLoad即使在 ViewDidLoad 中初始化后,UICollectionView 也必须使用非零布局参数进行初始化
【发布时间】:2016-10-20 04:01:32
【问题描述】:

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

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)
}

【问题讨论】:

  • 显示你的 collectionview Delegates 方法
  • 您似乎遇到了委托问题。使用此 UICollectionViewDelegate、UICollectionViewDataSource、UICollectionViewDelegateFlowLayout 更新您的委托
  • 您的代码中缺少布局项大小....layout.itemSize = CGSize(width: 100, height: 100)
  • 都没有用。
  • 您是否在您的班级中设置了那些委托比这应该起作用..我想知道您能解释一下这是什么意思宽度:view.frame.size.width。如果你想显示一个项目/行,你应该使用 tableView ......

标签: ios swift collectionview


【解决方案1】:

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

【讨论】:

  • 很高兴您回答了自己的问题。但请编辑以显示已更改的代码。
猜你喜欢
  • 2019-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-08
  • 2018-05-09
  • 1970-01-01
  • 2019-01-19
  • 1970-01-01
相关资源
最近更新 更多