iOS UICollectionView,如何动画数据源更改?

时间:2015-04-13 19:49:59

标签: ios objective-c animation ios6 uicollectionview

我正在使用UICollection视图,并希望对其数据源的更改进行动画处理。新数据源与旧数据共享很多项目,我想动画插入新项目并删除不再存在于数据源中的项目,同时保持所有其他单元格完好无损:

目前:[1,2,8,9] 更新:[1,2,3,9] 更改:插入3,删除8

是否有使用动画交换UICollectionView的数据源的示例?

我试过这个,这会导致集合视图闪烁,但是没有播放动画:

 [self.collectionView performBatchUpdates:^{

     [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
 } completion:^(BOOL finished) {

 }];

此方法会抱怨项目数量不匹配:

-(void)setDatasource:(NSMutableArray *)datasource
{

    NSMutableArray* _datasourceBackup = _datasource;


    //find out what is being added and deleted
    NSMutableArray* itemsToDelete = [NSMutableArray arrayWithArray:_datasource];
    DLog(@"delete raw: %lu", (unsigned long)itemsToDelete.count);
    [itemsToDelete removeObjectsInArray:datasource];
    DLog(@"delete filtered: %lu", (unsigned long)itemsToDelete.count);


    NSMutableArray* itemsToAdd = [NSMutableArray arrayWithArray:datasource];
    DLog(@"add raw: %lu", (unsigned long)itemsToAdd.count);
    [itemsToAdd removeObjectsInArray:_datasource];
    DLog(@"add filtered: %lu", (unsigned long)itemsToAdd.count);


    //1 update datasource
    _datasource = datasource;

    if(_datasourceBackup.count == 0)
    {
        //original load
        [self.collectionView reloadData];
    }else
    {
        [self.collectionView performBatchUpdates:^{

            //convert items to add/delete into index paths and give them to collection view to animate
            NSMutableArray* indexPathsToDelete = [NSMutableArray array];
            for(NSString* identifier in itemsToDelete)
            {
                NSInteger index = [_datasourceBackup indexOfObject:identifier];
                [indexPathsToDelete addObject: [NSIndexPath indexPathForRow:index inSection:0]];
            }
            if(indexPathsToDelete.count > 0 )
            {
                [self.collectionView deleteItemsAtIndexPaths:indexPathsToDelete];
            }


            NSMutableArray* indexPathsToInsert = [NSMutableArray arrayWithCapacity:itemsToAdd.count];
            for(NSString* identifier in itemsToAdd)
            {
                NSInteger index = [_datasource indexOfObject:identifier];
                [indexPathsToInsert addObject: [NSIndexPath indexPathForRow:index inSection:0]];
            }

            if(indexPathsToInsert.count > 0 )
            {
                [self.collectionView insertItemsAtIndexPaths:indexPathsToInsert];
            }


        } completion:nil];
    }
}

0 个答案:

没有答案