如何让 UICollectionView 连续水平滚动而不是创建第二行?

How do I get UICollectionView to continuously scroll horizontally instead of creating a second row?

调整 UICollectionView 的宽度以匹配单元格数 * 它们的宽度以防止 UICollectionView 在我的水平集合视图中创建第二行的正确方法是什么。

是否有特定的 CollectionView 实现方法允许我进行设置?

目前看起来像:

目前,我正在实现以下方法:

func numberOfSections(in collectionView: UICollectionView)

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewDelegateFlowLayout, sizeForItemAt indexPath: IndexPath)

首先将您的 collectionView FlowLayout scrollDirection 设置为水平。

let myColl:UICollectionView = {
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .horizontal
    let coll = UICollectionView(frame: .zero, collectionViewLayout: layout)
    return coll
}()

然后将您的 collectionview 高度约束设置为等于(或更小)单元格高度

myColl.heightAnchor.constraint(equalToConstant: 50).isActive = true

在这里设置你的单元格大小

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width-32, height: 50)
    }

对于任何想知道的人,Dilan 的回答也适用于使用故事板创建和链接的 UICollectionView。

只需执行 Dilan 在您的 viewDidLoad() 函数中建议的操作即可。

override func viewDidLoad() { myColl.heightAnchor.constraint(equalToConstant: 50).isActive = true }

确保您的 class(如果还不是 UICollectionViewController)subclasses UICollectionViewFlowDelegate。

class MyClass: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {}

如果不这样做,

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: view.frame.width-32, height: 50)
}

不会被调用。