swift - 即使滚动方向设置为水平,UICollectionView 也会垂直显示?
问题描述
我正在尝试UIScrollView
使用此代码水平绘制列表但无法正常工作?
let nib = UINib(nibName: cellIdentifier, bundle: nil)
collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier)
collectionView.collectionViewLayout = layout(withParentView: view)
self.collectionView.delegate = self
self.collectionView.dataSource = self
流布局方法
// #PRAGMA mark - UICollectionViewFlowLayout()
func layout(withParentView parentView: UIView) -> UICollectionViewFlowLayout {
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: 160, height: 65)
layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
return layout
}
这是委托和数据源方法
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 2
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! RowCollectionViewCell
if indexPath.row % 2 == 0 {
cell.backgroundColor = UIColor(red: 248/255, green: 248/255, blue: 248/255, alpha: 1)
}else {
cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
}
cell.label.text = "Field\(indexPath.row)"
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
return CGSize(width: 160, height: 65)
}
当我运行它时,它会显示这个(项目的垂直列表)。有什么我错过的吗。任何帮助,将不胜感激。
解决方案
我想你不明白是如何UICollectionViewFlowLayout
工作的。
流式布局使用基于行的布局。这对您意味着,如果您将滚动方向设置为水平,则单元格将按从上到下的行形式排列,直到没有更多可用空间,然后移动到下一行。
您可以通过将单元格的数量更改为更高的值来轻松验证这一点。(比如 10 个?)
我建议您观看此视频以更好地了解其UICollectionView
工作原理。
推荐阅读
- c# - 如何避免在客户端设置 DnsEndpointIdentity
- node.js - Nodemon 无法在 Docker 上使用 package.json 中的 npm 脚本
- docker - 为什么 hyper-v 虚拟机中的 docker 容器状态不正确?
- python - scikit-learn 中的高斯过程:在训练数据上表现良好,在测试数据上表现不佳
- reactjs - 使用 React JS 从 CloudFirestore 获取特定帖子
- java - 如何从我的 SQL 数据库中获取信息
- laravel - gcloud应用引擎laravel应用程序cron作业未执行
- flutter - 如何在 Flutter 中按顺序添加新的列表图块?当我添加新的时,它是按随机顺序添加的
- excel - Excel 图表 Y 轴在 360 度回滚回零
- google-chrome - 在 Travis CI 上的 Chrome 和 Firefox 中显示中文、韩文和日文字体