gpt4 book ai didi

ios - UICollectionViewFlowLayout,UICollectionView : changing screen orientation breaks cells arrangement

转载 作者:行者123 更新时间:2023-11-30 10:57:47 25 4
gpt4 key购买 nike

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
}

垂直方向 Vertical Orientation

水平方向 Horizontal Orientation

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

最佳答案

您可以尝试使用自动布局

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()

}

关于ios - UICollectionViewFlowLayout,UICollectionView : changing screen orientation breaks cells arrangement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53746415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com