swift - UICollectionView 必须使用非零布局参数初始化(UICollectionViewController StoryBoard)

标签 swift uicollectionview

我已经研究过了,但我不知道我的代码中缺少什么。我已经使用 Storyboard 并将 BrowseView 连接到 UICollectionViewController,并且我为我的单元使用了 Xib 文件,并且我已经将我的 xib 文件设置为我的类。

   class BrowseView: UICollectionViewController {

    let cellIdentifier = "Cell"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.delegate   = self
        collectionView?.dataSource = self

        let nib = UINib(nibName: "BrowseItemCell", bundle: nil)
        collectionView?.register(nib, forCellWithReuseIdentifier: cellIdentifier)
    }
}

extension BrowseView {

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

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! BrowseItemCell
        return cell
    }

}

最佳答案

这是在代码 UICollectionViewFlowLayout 中创建它的方式

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: frame, 
collectionViewLayout: layout)

或者如果 CollectionView 只是 ViewController 中的元素之一,则应该以这种方式显示

 let newCollection: UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    let collection = UICollectionView(frame: CGRect(x: 0, y: 0, width:0, height: 0), collectionViewLayout: layout)
    collection.isScrollEnabled = true
    return collection
 }()

关于swift - UICollectionView 必须使用非零布局参数初始化(UICollectionViewController StoryBoard),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45142129/

相关文章:

swift - 如何为 liter() 类型的 HKUnit 读取和写入数据?

ios - UISearchController 未在 UITableViewController 中搜索

ios - 不在每个单元格中使用带有 CollectionView 的 UITableView 中的可重用单元格

ios - UICollectionView 显示不同的单元格取决于方向

swift - 如何在 Swift 4 中仅将 NSButton 的一侧的角圆角化?

swift - 您是否需要从每个子类的函数调用父类(super class)的实现

swift - 为什么我们需要显式地将可选类型转换为 Any?

ios - 如何更改屏幕上尚未显示的单元格的属性?

ios - 快速拖放 - 在同一 collectionView 中一次移动多个项目

cocoa-touch - UICollectionViewCell 的子类不显示