根据屏幕/框架大小设置UICollectionViewCell的大小 - Swift

5

我有一个CollectionView,每个CollectionViewCell中都有一张图片。我想在任何给定的框架/屏幕尺寸下仅显示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)
    }

但是它无法正常工作并且出现了错误。最好的方法是什么?

4个回答

11

这是你的 Swift 代码:

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

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


1
如果我这样做,单元格之间会有空隙...而我不想要这些空隙,我希望在所有屏幕和所有方向上都有5像素的水平和垂直间隔。单元格的数量会增加和减少。你能帮忙吗? - Saty
在添加代理类时,不要忘记添加“UICollectionViewDelegateFlowLayout” - @JayprakashDubey - Deepak Chaudhary

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

2
在添加代理类时,不要忘记添加“UICollectionViewDelegateFlowLayout”。 - Deepak Chaudhary

1
尝试这个, 根据屏幕大小和方向指定collectionView单元格项的大小。 您可以查看this
希望这有所帮助。

1

针对Swift3和Xcode 8,解决水平间距问题的答案:

之前所有答案的问题在于,给定的单元格大小CGSizeMake(cellWidth, cellWidth)实际上占据了整个屏幕,没有留出边距线的空间,因此collectionView尝试通过每行少放一个元素和多余的间距来调整行/列间距。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    let linespacing = 5          //spacing you want horizantally and vertically
    let numberOfCell: CGFloat = 3   //you need to give a type as CGFloat
    let cellWidth = UIScreen.mainScreen().bounds.size.width / numberOfCell
    return CGSizeMake(cellWidth - linespacing, cellWidth - linespacing)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接