Swift 3: How to center horizontally the last row of cells in a UICollectionView with only one section?

Related searches

I'm using a UICollectionView with only one section. Here's some visualization:

[ x x x ]  
[ x x x ]  
[ x x   ] 

If the last row in the UICollectionView does not have all 3 cells filled, I'd like to center those cells like so:

[ x x x ]  
[ x x x ]  
[  x x  ] 

I've tried to implement solutions from the following places:

  1. How to center horizontally UICollectionView Cells?

  2. How to center align the cells of a UICollectionView?

However, the solutions shifts all the cells, and I'd like to only shift the LAST row if that last row doesn't contain X number of cells since I only have one section.

I know how to set insets, but I don't know how to achieve this with being only one section and trying to adjust the inset on the last row of cells.

I just started using UICollectionView and not sure how to go around this issue?

Sounds like you need everything a flow layout offers with a little customizations. Subclassing flow layout and overriding layoutAttributesForElements should do the job:

A quick and dirty implementation will basically ask FlowLayout to do the layout for a given rect, then figure out what items appear in the last row. If there are less than 3 items, then space them out evenly.

class LastRowCenteredLayout: UICollectionViewFlowLayout {
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard var elementAttributes = super.layoutAttributesForElements(in: rect) else { return nil }
        guard elementAttributes.count > 0 else { return elementAttributes }

        elementAttributes = elementAttributes.map { $0.copy() as! UICollectionViewLayoutAttributes }

        let minY = elementAttributes.last!.frame.minY
        let lastRowAttrs = elementAttributes.reversed().filter { $0.frame.minY == minY }

        guard lastRowAttrs.count < 3,
                let first = elementAttributes.first,
                let last = elementAttributes.last else {
            return elementAttributes
        }

        let horizontalPadding = rect.width - first.frame.minX - last.frame.maxX
        let horizontalShift = horizontalPadding / 2.0

        for attrs in lastRowAttrs {
            attrs.frame = attrs.frame.offsetBy(dx: horizontalShift, dy: 0)
        }

        return elementAttributes
    }
}

Note that if you plan on animating insertions/deletions, you should also override layoutAttributesForCellWithIndexPath: and ensure it returns consistent results.

Apple has a guide on FlowLayout with a section dedicated to subclassing.

Sample Playground:

https://gist.github.com/AnuragMishra/0a694dfa9be1a5eab9fc7368b69812ad

ios, Sounds like you need everything a flow layout offers with a little customizations. Subclassing flow layout and overriding� While rottenoats answer is great, it has an extra spacing bug and doesn't use much of the available swift 3 syntax. I've fixed that and reduced the number of dependencies to local variables. I've fixed that and reduced the number of dependencies to local variables.

The short answer is: you can't, using the provided UICollectionViewFlowLayout by Apple

The longer answer is: You're going to have to create a customer UICollectionViewLayout subclass and place the element yourself. Start by going through this tutorial. Then you should have a better understanding of the inner workings to be able to create your own custom layout.

Swift 3: How to center horizontally the last row of cells in a - iOS, I'm using a UICollectionView with only one section. Here's some visualization: [ x x x ] [ x x x ] [ x x ] If the last row in the UICollectionView does not have all 3 cells � UPDATE: I added a simpler version of the finished project (can be found at the bottom of the tutorial) so it will be easier to adopt the concepts shown in this tutorial to your own needs. Well, it…

strong textyou can do this simple calculation in your collectionViewLayout function.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    //return itemSize
    let spaceBetweenCell :CGFloat = 0
    let screenWidth = UIScreen.main.bounds.size.width - CGFloat(2 * spaceBetweenCell)
    let totalSpace = spaceBetweenCell * 1.0
    if indexPath.row == categories.count-1 {
      // check if last cell is odd
      if categories.count % 2  == 1 {
        return CGSize(width: screenWidth , height: (screenWidth-totalSpace)/4) // all Width and  same previous height
      }else {
        return itemSize
      }
    }else{
      return itemSize
    }
  }

Uicollectionview horizontal scroll one row, The collection view's layout should be a single horizontal row; I assume that section fulfills one goal from the list and moves us one step closer to the final solution. swift uicollectionview row not display full ios - UICollectionView Custom Cell Only one product is presented at the center of the screen, and users can see� We’ll simply add the section index to the current number of items in each row (3). So for example, the first section (index 0) will have 3 items in each row, the second section will have 4 items in each row, the third section will have 5 items in each row, etc. We only need to change the declaration of fraction.

Just add another empty cell at the end, that is full-width, the cells which are before will center

Collection View with Sticky Rows and Columns: Step by Step Tutorial, Each subsequent section fulfills one goal from the list and moves us In our project 3 cells fit the screen horizontally which results in a grid The only thing that is left is small utility method that converts row and column into IndexPath : Sticky Grid Collection View: Implementing From Scratch - Final Demo. The number of prototype cells. This property controls the specified number of prototype cells for you to configure in your storyboard. Collection views must always have at least one cell and may have multiple cells for displaying different types of content or for displaying the same content in different ways. Layout. The layout object to use.

How to center align the cells of a UICollectionView?, uicollectionview scroll one cell at a time swift for any horizontal scrolling collection view with flow layout and only one section: Swift 3: How to center horizontally the last row of cells in a , How to center align the cells of a UICollectionView? UICollectionView contains several key components, as you can see below: Take a look at these components one-by-one: UICollectionView: The main view in which the content is displayed, similar to a UITableView. Like a table view, a collection view is a UIScrollView subclass. UICollectionViewCell: This is similar to a UITableViewCell in a table

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.

This wikiHow teaches you how to center an Excel spreadsheet in the middle of the page, using a computer. You can center your spreadsheet horizontally and vertically, using the custom margin options on a desktop computer. You can't change the margin options or center a worksheet in Excel mobile on a phone or tablet.