Search code examples
iphoneiosuicollectionviewsonypstcollectionview

Overriding layoutAttributesForElementsInRect: of UICollectionView / PSTCollectionView causes visible cell to reload


I want to mimic the features of gallery app provided in Sony Xperia in iPhone app. I gallary app, images are shown in grid grouped by date and the first photo of the section is twice in size than the others. On pinching out / in, all photos get zoom out / in.

enter image description here

I used PSTCollectionView as suggested by Lithu T.V and have created a custom layout. In that layout I have overridden - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect. Bellow is the code for same.

// called continuously as the rect changes
 - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
 NSArray *attribs = [super layoutAttributesForElementsInRect:rect];

 NSMutableArray *arrmFrames=nil;
 for (int i=0;i<attribs.count;i++) {

     UICollectionViewLayoutAttributes *attributesInitial=[attribs objectAtIndex:0];

     UICollectionViewLayoutAttributes *attributes=[attribs objectAtIndex:i];

     //Take initial frame from first cell
     if(i==0)
    fFirstCellsY = attributes.frame.origin.y;

     //while Y is constant, save the adjusted frames for next cells
     else if(attributes.frame.origin.y<fFirstCellsY+attributesInitial.frame.size.height)
     {
      if(arrmFrames==nil)
          arrmFrames=[[NSMutableArray alloc]init];

         attributes.frame=CGRectMake(attributes.frame.origin.x, attributesInitial.frame.origin.y, attributes.frame.size.width, attributes.frame.size.height);
         [arrmFrames addObject:NSStringFromCGRect(CGRectMake(attributes.frame.origin.x, attributes.frame.origin.y+attributes.frame.size.height+10, attributes.frame.size.width, attributes.frame.size.height))];
     }

     //Adjust the frame of other cells
     else
     {
         CGRect frame = attributes.frame;
         attributes.frame=CGRectFromString((NSString*)[arrmFrames objectAtIndex:0]);
         [arrmFrames removeObjectAtIndex:0];
         [arrmFrames addObject:NSStringFromCGRect(frame)];
     }

 }

 }

return attribs;
}

This works and the layout is looking like I wanted. By this method more cells become visible than those by using default layout and my layout looks OK. but when I scroll down then some visible cells are getting reloaded. I guess the reason is the delegate method - (PSUICollectionViewCell *)collectionView:(PSUICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath is getting called before - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect which is there in my custom layout. and so the cells which were not visible in default layout but visible in custom layout are reloaded late.

How can I overcome this?


Solution

  • Use UICollectionView If app is supposed to support in less than 5.0 use PSTCollectionView

    A nice startup