如何根据设备屏幕大小调整集合视图单元格的大小?

Chr*_*sen 17 ios uicollectionview ios10

我注意到单元格总是遵循尺寸检查器中的定义.即使我已经应用了UICollectionViewDelegateFlowLayout.

在此输入图像描述

在此输入图像描述

这就是它的外观.但我希望这些细胞看起来更像是在更小的iPhone屏幕上.

在此输入图像描述

Mar*_*mov 40

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let height = view.frame.size.height
    let width = view.frame.size.width
    // in case you you want the cell to be 40% of your controllers view
    return CGSize(width: width * 0.4, height: height * 0.4)
}
Run Code Online (Sandbox Code Playgroud)

  • 它是一个UICollectionViewDelegateFlowLayout方法.UICollectionViewDelegateFlowLayout继承自UICollectionViewDelegate,这意味着您应该在添加此方法后实现此方法并将协议UICollectionViewDelegate更改为UICollectionViewDelegateFlowLayout,否则此方法不会被调用 (6认同)

Vas*_* D. 13

斯威夫特4

你可以这样做:

class yourClassName: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {


    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
            return CGSize(width: self.myCollectionView.frame.height / 6 * 5, height: self.myCollectionView.frame.height / 6 * 5)

        }


}
Run Code Online (Sandbox Code Playgroud)

self.myCollectionView是您的集合视图的参考项目,
它是重要的实现UICollectionViewDelegateFlowLayout

而且因为它不适合另一个单元格,所以只有一行.


Dan*_*ond 5

在设置像元大小而不是数字时,您应该尝试使用一个简单的方程式:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: view.frame.width / 2, height: 350)
    }
Run Code Online (Sandbox Code Playgroud)

将其除以2将表示该单元格始终是屏幕大小的一半,这不包括您调用的minimumLineSpacing函数和/或UIEdgeInset方法。希望这可以帮助。


Roh*_*ana 5

在 swift 3 中,您可以使用collectionViewLayout属性根据屏幕调整集合视图单元格的大小。

IE

   let numberOfCell = 3
   let cellSpecing = 10
   if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        layout.itemSize = CGSize(width: (screenSize.width - (cellSpecing * (numberOfCell + 1))) / numberOfCell, height: cellHeight)
        layout.invalidateLayout()
    }
Run Code Online (Sandbox Code Playgroud)


Kar*_*ngh 5

有些人可能也需要这样做:在 Storyboard 中,转到 Collection View 中的 collectionviewFlowLayout(黄色立方体),然后转到 Size Inspector,确保“Estimated Size”设置为“None”。