UICollectionViewFlowLayout、UICollectionView:更改屏幕方向会破坏单元格排列

Posted

技术标签:

【中文标题】UICollectionViewFlowLayout、UICollectionView:更改屏幕方向会破坏单元格排列【英文标题】:UICollectionViewFlowLayout, UICollectionView: changing screen orientation breaks cells arrangement 【发布时间】:2018-12-12 15:35:17 【问题描述】:
let numberOfCellsPerRow: CGFloat = 3

override func viewDidLoad() 
    super.viewDidLoad()

    layout = UICollectionViewFlowLayout()
    layout.minimumLineSpacing = 0
    layout.minimumInteritemSpacing = 0

    collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height), collectionViewLayout: layout)
    collectionView.backgroundColor = .clear
    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")

    view.addSubview(collectionView)


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
    return 3


func numberOfSections(in collectionView: UICollectionView) -> Int 
    return 1


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize 
    let cellWidth = (view.frame.width - max(0, numberOfCellsPerRow - 1) * layout.minimumInteritemSpacing) / numberOfCellsPerRow

    return CGSize(width: cellWidth, height: 75.0)


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    let itemCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    itemCell.backgroundColor = .black

    return itemCell

垂直方向

水平方向

我希望所有单元格都在同一行。为什么第一个单元格的左侧有一些边距(水平方向)?在我以水平方向启动应用程序的情况下,垂直方向的单元格之间会出现一些空间。

【问题讨论】:

【参考方案1】:

您可以尝试使用自动布局

self.collectionView.translatesAutoresizingMaskIntoConstraints = false

NSLayoutConstraint.activate([

    self.collectionView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
    self.collectionView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
    self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor),
    self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),

])

或者刷新viewWillTransition里面的框架

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) 

    super.viewWillTransition(to: size, with: coordinator)

    self.collectionView.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)

    self.collectionView.collectionViewLayout.invalidateLayout()


【讨论】:

以上是关于UICollectionViewFlowLayout、UICollectionView:更改屏幕方向会破坏单元格排列的主要内容,如果未能解决你的问题,请参考以下文章