简体   繁体   中英

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.

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 .

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

Answer for Swift3, Xcode 8 with horizantal spacing fixed:

The issue with all earlier answer is that cell size is given CGSizeMake(cellWidth, cellWidth) actually takes all screen leaving no room for margin lines due to which collectionView tries to adjust the row/column spacing by taking one element less in each row and unwanted extra spacing.

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

Try this, To specify Size of collectionView cell items according to screen size and orientation. You can have a look at this

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM