即使滚动方向设置为水平,UICollectionView仍显示垂直?

Vis*_*l16 4 uicollectionview swift uicollectionviewflowlayout

我正在尝试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
Run Code Online (Sandbox Code Playgroud)

流式布局法

// #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
}
Run Code Online (Sandbox Code Playgroud)

这是委托和数据源方法

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)
}
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

Rak*_*tri 6

流布局使用基于行的布局。这对您来说意味着,如果您将滚动方向设置为Horizo​​ntal ,那么单元格将从上到下排列成一行,直到没有更多空间可用,然后移至下一行。

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


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