Search code examples
iosuicollectionviewuicollectionviewlayout

Animate change in collectionView Insets


I have a small collectionView with 2 cells. That is centred on the screen vertically. When user selects a cell a new cell appears in the collection view and collection view changes its insets accordingly to middle 3 cells vertically in the screen. However this change is not smooth, it is jumpy. Is there any way to animate collectionView inset change ?

   -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
    NSArray* array = [super layoutAttributesForElementsInRect:rect];

    UICollectionViewLayoutAttributes* att = [array lastObject];
    if (att){
        CGFloat lastY = att.frame.origin.y + att.frame.size.height;
        CGFloat diff = self.collectionView.frame.size.height - lastY;
        if (diff > 0){
            UIEdgeInsets contentInsets = UIEdgeInsetsMake(diff/2, 0.0, 0.0, 0.0);
            self.collectionView.contentInset = contentInsets;
        }
        self.diff = diff;
    }
    return array;
}

Solution

  • It did not seem possible to animate the collectionView insets without creating custom UICollectionViewLayout so I changed the logic and implemented changing position of the cell instead of changing the insets of collection view. This gives real smooth animation !

    -(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
        NSArray* array = [super layoutAttributesForElementsInRect:rect];
    
        UICollectionViewLayoutAttributes* att = [array lastObject];
        if (att){
            CGFloat lastY = att.frame.origin.y + att.frame.size.height;
            CGFloat diff = self.collectionView.frame.size.height - lastY;
            if (diff > 0){
                for (UICollectionViewLayoutAttributes* a in array){
                    a.frame = CGRectMake(a.frame.origin.x, a.frame.origin.y + diff/2, a.frame.size.width, a.frame.size.height) ;
                }
            }
        }
        return array;
    }