UICollectionViewCell size according to screen / FrameSize Swift

I have a View collection with an image in the CollectionCell. I want to have only 3 cells for any frame / screen size. How to implement it. I wrote code based on this post

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

But it does not work and does not give an error. What is the best way to do this.

+4
source share
3 answers

Here is your quick code:

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, CGFloat Int.

+7

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

Swift3, Xcode 8 :

, . CGSizeMake (cellWidth, cellWidth) , margin, - 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)
 }
0
source

Source: https://habr.com/ru/post/1607316/


All Articles