UICollectionViewFlowLayout,UICollectionView:更改屏幕方向会中断单元格排列

时间:2018-12-12 15:35:17

标签: ios swift uicollectionview uikit

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

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

1 个答案:

答案 0 :(得分:0)

您可以尝试使用自动布局

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

}