我已经研究过了,但我不知道我的代码中缺少什么。我已经使用 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/