UICollectionView在单元格的每一侧插入单元格

时间:2015-11-14 06:39:56

标签: ios objective-c uicollectionview uicollectionviewlayout

我尝试在水平单行UICollectionView中设置插入动画。说细胞看起来像这样......

            c3    c6    c9    c12

我想在c6周围插入像这样的单元格......

c3    c4    c5 <<-c6->> c7    c8    c9    c12

所以我必须面对挑战:(a)让c6在整个动画中保持在相同位置(在相同的contentOffset处),以及(b)让新单元格在c6&c;内容偏移和分散。

我尝试过的方法是:(a)在开始动画时移动内容偏移量;对于(b)在UICollectionViewFlowLayout子类中,尝试回答{{}中正确的布局属性1}}。

这就是看起来像......

initialLayoutAttributesForAppearingItemAtIndexPath

布局要求我的视图控制器输入这样的插入属性(我从未扩展过像这样的协议,但我检查控件是否按预期在调试器中流动)...

// in the vc that has the collection view.
- (void)insertAroundIndexPath:(NSIndexPath *)indexPath {
    NSInteger index = indexPath.row;

    // code here to insert items in my model array, two on each side of indexPath
    NSArray *indexPaths = // code here to compute the index paths of new items
    // I've tested the above and it works 

    // move the content offset
    CGFloat itemWidth = [self paddedItemSize].width;
    CGFloat offsetDelta = 2.0 * itemWidth;  // since we are inserting 2 items
    CGPoint contentOffset = self.collectionView.contentOffset;
    CGPoint newContentOffset = CGPointMake(contentOffset.x + offsetDelta, contentOffset.y);

    // will set the contentOffset to newContentOffset, but first...
    // record the layoutAttributes of the place where insertion is happening
    UICollectionViewFlowLayout *layout = (UICollectionViewFlowLayout *)self.collectionView.collectionViewLayout;
    // this is a property on my vc
    self.insertionLayoutAttributes = [layout layoutAttributesForItemAtIndexPath:indexPath];

    // do the insertion
    [self.collectionView insertItemsAtIndexPaths:indexPaths];
    // change the content offset
    [self.collectionView setContentOffset:newContentOffset animated:NO];
}

这很有道理,对吗? // my CollectionViewFlowLayout.h @interface CollectionViewLayout : UICollectionViewFlowLayout @end @protocol CollectionViewLayoutDelegate <UICollectionViewDelegateFlowLayout> - (UICollectionViewLayoutAttributes *)insertionLayoutAttributes; @end // my CollectionViewFlowLayout.m - (UICollectionViewLayoutAttributes *)initialLayoutAttributesForAppearingItemAtIndexPath:(NSIndexPath *)itemIndexPath { id<CollectionViewLayoutDelegate> delegate = (id<CollectionViewLayoutDelegate>)self.collectionView.delegate; UICollectionViewLayoutAttributes *attributes = [delegate insertionLayoutAttributes]; return (attributes)? attributes : [super initialLayoutAttributesForAppearingItemAtIndexPath:itemIndexPath]; } 这件事有效,但并不完全。我想要保持固定的单元格最终会在同一个地方停留,但它会先消失,因为集合视图会为新单元格设置空间开放动画(我不明白为什么应该这样做)。

插入起始位置根本不起作用。无论我如何订购,新单元格(以及作为插入中心的单元格)都会从集合视图的左侧进入。

当我在调试器中检查contentOffset时,attributes值看起来是正确的,但动画是混合的。任何想法都赞赏。

0 个答案:

没有答案
相关问题