【问题标题】:UICollectionView showing vertically even when scroll direction is set to horizontal?即使滚动方向设置为水平,UICollectionView 也会垂直显示?
【发布时间】:2018-08-27 08:37:52
【问题描述】:

我正在尝试使用此代码水平绘制 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)
}

当我运行它时,它会显示这个(项目的垂直列表)。有什么我错过的吗。任何帮助将不胜感激。

【问题讨论】:

    标签: swift uicollectionview uicollectionviewflowlayout


    【解决方案1】:

    我想你不明白UICollectionViewFlowLayout 的工作原理。

    流式布局使用基于行的布局。这对您来说意味着如果您将滚动方向设置为水平,那么单元格将以从上到下的线条形式排列> 直到没有更多可用空间,然后继续下一行。

    您可以通过将单元格数更改为更高的值来轻松验证这一点。 (比如 10 个?)


    我建议您观看此video,以更好地了解UICollectionView 的工作原理。

    【讨论】:

    • 我已将一些单元格更改为 10 和 field8,field9 转到下一列,现在它可以水平滚动。但是我怎样才能实现单个单元格会转到下一列呢?
    • @Vishal16 尝试减小集合视图大小或增加项目大小。
    猜你喜欢
    • 1970-01-01
    • 2015-05-31
    • 2017-07-05
    • 2020-03-08
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多