Collection view grid last row appears differently despite equal widths - swift iOS

uicollectionview 2 columns swift 4
uicollectionviewflowlayout
uicollectionviewdelegateflowlayout
uicollectionview 2 cells per row
collection view in xcode 11
swift grid view
custom collection view cell swift

I've a fixed grid of collection view cells (UICollectionView) but the cells in the bottom row always appears with a slightly smaller width on screen. The frame size (or bounds) and calculated width used within collectionViewLayout: UICollectionViewLayout sizeForItemAt are the same for all rows.

        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    let settings = currentContents[indexPath.item]
    let height = CGFloat(30)

    // https://stackoverflow.com/questions/54915227/uicollectionview-remove-space-between-cells-with-7-items-per-row
    var cellWidth = CGFloat()
    let availableWidth = collectionView.bounds.size.width
    print("available width", availableWidth)
    let minimumWidth = floor(availableWidth / collectionContents.cellsPerRow5)
    print("minmum width", minimumWidth)
    cellWidth = minimumWidth * settings.portion - 1
    print("cell width", cellWidth)

    return CGSize(width: cellWidth, height: height)
}

I'd like to get the bottom row to line up with the other rows, but can't imagine what is happening that is changing the widths after returning the value in the layout delegate method (or how to fix).

UIKit does not like values with more than 2 decimals, round them or it will do it for you.

Here, UICollectionViewFlowLayout rounds your cell size and starts to fill the lines with an "interitemspacing" at least equal to the minimumInteritemSpacing you specified. On the last line, it used exactly the minimumInteritemSpacing value and doesn't fill entirely the line.

Fix it using better rounded values, giving the illusion that all is perfectly aligned.

I usually use those extensions:

extension CGFloat {
    func xx_rounded(_ rule: FloatingPointRoundingRule = .down, toDecimals decimals: Int = 2) -> CGFloat {
        let multiplier = CGFloat(pow(10.0, CGFloat(decimals)))
        return (self * multiplier).rounded(.down) / multiplier
    }
}

extension CGSize {
    func xx_rounded(rule: FloatingPointRoundingRule = .down, toDecimals: Int = 2) -> CGSize {
        return CGSize(
            width: width.xx_rounded(rule, toDecimals: toDecimals),
            height: height.xx_rounded(rule, toDecimals: toDecimals)
        )
    }
}

Change:

return CGSize(width: cellWidth, height: height)

to

return CGSize(width: cellWidth, height: height).xx_rounded()

Create a grid table with fixed number of rows and , Collection view grid last row appears differently despite equal widths – swift iOS. Posted on 28th May 2019 by DrWhat. I've a fixed grid of collection view cells  Collection view grid last row appears differently despite equal widths - swift iOS Hot Network Questions Air conditioning: Frequent on-off of outdoor unit or stay on for long duration

Just replace

cellWidth = (minimumWidth * settings.portion) - 0.5

WITH

cellWidth = (minimumWidth * settings.portion)

Specified minimumInteritemSpacingForSectionAt to 0.5 instead of 0

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.5
}

CVTVCell.swift

Just reload your UICollectionView in awakeFromNib method after your data set into currentContents. Please refer below sample code.

override func awakeFromNib(){
    super.awakeFromNib()
    currentContents = collectionContents.allEndings[0]
    self.cView.reloadData()
}

Download code from here

Collection View with Sticky Rows and Columns: Step by Step Tutorial, Create a grid table with fixed number of rows and columns of variable widths Firstly, the cells in the last row of the table do not align perfectly with the cells above. This issue, while minor in the example project, can appear larger depending on cell contents func collectionView(_ collectionView: UICollectionView, layout  Collection view grid last row appears differently despite equal widths - swift iOS. Hot Network Questions Is it a bad idea to use other professors' Youtube videos as

The best way I found was to capture the remaining space (minus 1 to avoid rounding up) after calculating the initial column width, and then use this remaining space for additional columns.

For a two column example:

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    if indexPath.item == 0 || indexPath.item == 1
    { rowHeight = 40 }
    else { rowHeight = 30 }
    var cellWidth = CGFloat()
    let minimumWidth = floor(availableWidth / numberOfColumns)
    var columnPortion = CGFloat()
    let columnNumber = indexPath.item % Int(numberOfColumns)
    switch columnNumber
    {
    case 0:
        columnPortion = columnPortion1
        cellWidth = minimumWidth * columnPortion - 10
        remainder = availableWidth - cellWidth - 1
    case 1:
        columnPortion = columnPortionFinal
        cellWidth = remainder
    default:
        break
    }
    return CGSize(width: cellWidth, height: rowHeight)
}

Creating A Custom UICollectionViewLayout in Swift, In this article you will learn how to implement collection view that has sticky rows To design a grid with arbitrary number of sticky rows and columns we should and vertical scroll, the cells placement does not seem to be correct. xOffset += itemSize.width } // 6 yOffset += rowAttrs.last?.frame.height ?? Collection view grid last row appears differently despite equal widths - swift iOS Hot Network Questions Did Euler make the elementary mistake √-2 √-3 = √6?

iOS Tutorial: Want your Swift app to scroll in two directions, like , UICollectionView in iOS is a very useful and powerful class for displaying large A common use case for a UICollectionView is displaying a grid of items instead of rows When the bounds change on a scroll, the collection view needs a way to The final piece needed when creating a custom layout is indicating when the  We have hard coded it to 20. sizeForItemAtIndexPath sets the width and height of the invidual cells. This value decides when a new row will be started. Generally a new row will start if the remaining space in the current row is less than the size of the Cell. // // ViewController.swift // ImageGrid // // Created by Amit Sengupta on 10/4/15.

Incorrect spacing between cells UICollectionView : swift, Want to give users a way to casually explore different categories of Independently scrolling rows can help you achieve this effect. Since the images are in sort of a grid, a Collection View seems like a One final loose end to tie up. The width is just the Collection View width divided by four, and the  Tutorial to Create GRID VIEW using collection view in Swift 3 (IOS) February 12, 2017 March 18, 2017 Techno Code LLP 0 Comments Code Snippets , Coding , Grid View iOS , iOS , iPhone Application Development , Mobile , Mobile Application Development , Technology

Equally Spaced UICollectionView Cells - Nicholas Babo, The cells in the collection view are not specific in size, as its supposed to be a list of tags Language is Swift 4 and Im targeting iOS 10.3. If all your cells are equal width, or you know how many cells you want per graphical row you can adjust the analysis and tips on how to improve your sleep despite all of these factors. 1. It only appears when I use the UI-scaling feature in Windows. If the scale is set to 100%, no row is clipped, but if I use 125% the last row is clipped in half. 2. Using WPF Inspector I noticed that the ActualHeight and ActualWidth of the RadGridView is not integer numbers when using scaling, but I don't know if its related. 3.

Comments
  • Can you please share sample demo code with us
  • @iMHiteshSurani - which demo code do you mean? I have the full collectionViewLayout method where the cell width is set. If I delete everything but the borders in cellforitem at index path, the issue is still there - although it does seem a little less pronounced.
  • If I remove the settings.portion value - so that all cells in the row are equal width - then the problem disappears. Perhaps there is a better way to assign the proportion of the total row for each column of cells? Currently, the sum of all setting.portion values simply equals the number of columns. 1st column- portion: CGFloat(1.4), and all other portion: CGFloat(0.9)
  • I created and uploaded a project to demo the problem: github.com/DrWhen/Last-row-in-grid-error
  • Thanks - that makes a lot of sense, and gets very close to the solution in a very easy way. Only... in the GitHub project, if you do your fix, go to the offending screen (Articles and Adjectives) and choose the lowest value in the picker (Adjective with indefinite article ('a')), then the spacing issue is still there?!?
  • I changed your sizeForItemAt method and used let width = availableWidth / CGFloat(collectionContents.cellsPerRow5); return CGSize(width: width, height: 30).xx_rounded() I don't know what -1 & settings.portion are supposed to do.
  • I use settings.portions so that some columns are wider than others. For the 5 cells in the row - .portions are 1.4 for the first column and 0.9 for the other 4 columns. I need to be able to do this. "-1" was a way also to cope with left over remainders.
  • If you remove -1?
  • On some devices (eg X), without the -1 the total widths is larger than the row width and it spills onto next row and destroys the grid. On Git Hub, DeutschGramma.zip shows this. Updating this file with your approach, file with today's date - the problem occurs if you navi to "Articles and Adjectives" and choose the lowest value in the picker ("Adjective with indefinite article ('a')"). Bottom row of grid.
  • Thanks for taking a look. While this solution does fix the issue on some devices in some orientations, it does not work in all cases. I put the entire project, with the above changes, onto the same GitHub folder for download. When running - go to "Artilcle and Adjective Endings" to see grid table. If you run this in portrait on an iPhone 8, the grid breaks completely, or on iPad Pro, the bottom row is again different to other rows. Also if you use the picker to set values in table, the picker value "Adjective with indirect article" also mucks up the last row.