Joe Blow Joe Blow - 1 year ago 84
iOS Question

In a UICollectionView, the cells will not sit on the bottom

Note it turned out it was a simple mistake the cells would not "sit on the bottom". However, it's an interesting question: "how to move the cells up and down." Below a brute force solution: writing your own flow layout.

I was amazed that the only way to do it is entirely subclass

and write some tricky code in

It's possible this will help someone in the future, as there is very little example code for
around. Hope it helps.


It turns out the reason my cells would not sit on the bottom was that I previously had this in my UICollectionViewController...

[super viewDidLoad];
// the following code is very useful to, for example,
// "nudge short lists towards the middle..." - if you want the list
// to more sit in the middle of the screen, when only a few items.
cvHeight = CGRectGetHeight(self.collectionView.bounds);
[self.collectionView setContentInset:
UIEdgeInsetsMake(cvHeight * 0.175, 0, cvHeight * 0.30, 0) ]; //top,l,b,r

of course, when I changed to a "full-view cell size" (one cell per screen), that code fails.

I have a simple UICollection view which is the width of an iPhone and about 250 high. The cells are the exact same size as the collection view.

The cells will not center, they always site high. (i.e., outside the view.)

enter image description here

My collection view "sizes" in storyboard are all just zero. What could be the problem?

Answer Source

Here's one "brute force" way to solve the problem -- write your own FlowLayout!!

It works ...

@interface SimpleLayout : UICollectionViewFlowLayout


// this is a vanilla horizontal paging layout, which
// solves the bizarre "too high" problem!!!

@implementation SimpleLayout

    self = [super init];
    if (self) { [self initialize]; }
    return self;

-(id)initWithCoder:(NSCoder *)aDecoder
    self = [super initWithCoder:aDecoder];
    if (self) { [self initialize]; }
    return self;

    self.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.minimumInteritemSpacing = 0.0f;
    self.minimumLineSpacing = 0.0f;

    return [super collectionViewContentSize];


-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    NSMutableArray *allItems =
     [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    for (UICollectionViewLayoutAttributes *attribute in allItems)
        NSLog(@"attribute.frame.origin.y  ..... %f", attribute.frame.origin.y );

        attribute.frame = CGRectMake(
                    attribute.frame.origin.x, attribute.frame.origin.y + 34,
                    attribute.frame.size.width, attribute.frame.size.height);

        // "go figure" ... add 34

    return allItems;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download