Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionViewCell Size According to Screen/ FrameSize Swift

I have a collection View with an image in each collectionViewCell. I want to have only 3 cells for any given frame/ screen size. How do I implement this. I have written some 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 its not working and giving an error. What is the best way to do this.

like image 577
Anuj Arora Avatar asked Sep 14 '15 17:09

Anuj Arora


People also ask

How do I set the height and width of a collectionView cell?

Here's a WWDC video demoing this technique. class MyLayout: UICollectionViewFlowLayout { override func prepare() { super. prepare() guard let collectionView = collectionView else { return } itemSize = CGSize(width: ..., height: ...) } }


2 Answers

Here is your swift 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)
}

Here the type of numberOfCell must be a CGFloat because UIScreen.mainScreen().bounds.size.width return a CGFloat value so if you want to divide it with numberOfCell then type numberOfCell must be CGFloat because you can not divide CGFloat with Int.

like image 130
Dharmesh Kheni Avatar answered Sep 26 '22 13:09

Dharmesh Kheni


Here is Swift 3 code and you to have implement 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)
}
like image 42
Varun Naharia Avatar answered Sep 22 '22 13:09

Varun Naharia