根据Screen/FrameSize Swift的UICollectionViewCell大小

Anu*_*ora 4 ios uicollectionviewcell swift

我有一个集合视图,每个集合ViewCell中都有一个图像.对于任何给定的帧/屏幕尺寸,我想只有3个单元格.我该如何实现呢.我已根据这篇文章编写了一些代码

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let numberOfCell = 3
    let cellWidth: CGFloat = [[UIScreen mainScreen].bounds].size.width/numberOfCell
    return CGSizeMake(cellWidth, cellWidth)
    }
Run Code Online (Sandbox Code Playgroud)

但它没有工作并给出错误.做这个的最好方式是什么.

Dha*_*esh 9

这是你的快捷代码:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

    let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
    let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
    return CGSizeMake(cellWidth, cellWidth)
}
Run Code Online (Sandbox Code Playgroud)

这里的类型numberOfCell必须是CGFloat因为UIScreen.mainScreen().bounds.size.width返回CGFloat,所以如果你想用它除以值numberOfCell那么类型numberOfCell必须是CGFloat因为你不能分割CGFloat使用Int.


Var*_*ria 6

这是Swift 3代码,你有实现 UICollectionViewDelegateFlowLayout

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
    let cellWidth = UIScreen.main.bounds.size.width / numberOfCell
    return CGSize(width: cellWidth, height: cellWidth)
}
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记在添加委托类时添加"UICollectionViewDelegateFlowLayout" (2认同)