如何根据设备屏幕调整UICollectionViewCell的大小

问题描述 投票:0回答:1

我有一个带有自定义单元格的UICollectionView,但是,我试图在UICollectionView上施加约束,因此它始终是屏幕宽度的一半和屏幕高度的一半。我不断遇到的一个问题是,虽然UICollectionView根据应用程序部署在哪个设备上而变化,但UICollectionViewCells拥有完全相同的像素宽度和高度尺寸。这是我尝试实现的代码,以使每个单元格的高度和宽度与CollectionView相同。

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

但是,此代码不起作用,因为单元格的大小只是在UICollectionView的大小检查器中指定的值。

enter image description here

我无法弄清楚我的代码在做什么错。提前非常感谢您的帮助。

ios swift uicollectionview uicollectionviewcell
1个回答
0
投票
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width: view.frame.width, height: view.frame.height) }
© www.soinside.com 2019 - 2024. All rights reserved.