collectionView Insets中的动画更改

时间:2014-04-21 07:33:58

标签: ios uicollectionview uicollectionviewlayout

我有一个带有2个单元格的小collectionView。这是垂直居中的屏幕。当用户选择一个单元格时,集合视图中会出现一个新单元格,而集合视图会在屏幕中相应地将其插图更改为中间3个单元格。然而,这种变化并不顺利,它是跳跃的。有没有办法为collectionView插入更改设置动画?

   -(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;
}

2 个答案:

答案 0 :(得分:3)

似乎无法在不创建自定义UICollectionViewLayout的情况下为collectionView insets设置动画,因此我更改了逻辑并实现了更改单元格的位置,而不是更改集合视图的insets。这给了真正流畅的动画!

-(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;
}

答案 1 :(得分:0)

从iOS 12开始,ila的答案似乎不再准确-以下代码显示了动画插图对我的影响:

if !disableCustomInsets {
    UIView.animate(withDuration: 0.2, animations: {
        self.disableCustomInsets = true
        self.collectionViewLayout.invalidateLayout()
    }, completion: nil)
}