iOS 在collectionView顶部无缝插入数据效果
想要达到类似抖音在顶部插入数据的效果,不能用peformbatchupdate, 因为他的回调会有延迟,这里要先调用
[CATransaction setDisableActions:YES]; 关闭动画效果,然后在顶部插入数据,之后在滚动到插入之前的第一个数据的位置,就达到了从视觉上插入的效果
直接上代码
- (void)insertFeedsAtTop:(NSArray<NSObject *> *)instances completion:(void (^)(BOOL))completion
{
if (instances.count == 0) {
completion ? completion(YES) : nil;
}
dispatch_sync_on_main_queue(^{
NSMutableArray *privateCardInstances = [self valueForKey:@"dataSource"]];
if (![privateCardInstances isKindOfClass:[NSMutableArray class]]) {
return;
}
[CATransaction setDisableActions:YES];
NSIndexSet *idxs = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, instances.count)];
[privateCardInstances insertObjects:instances atIndexes:idxs];
NSInteger endItem = 0;
for (CSCardInstance *pIns in instances) {
endItem += pIns.children.count;
}
NSMutableArray *indexPathes = NSMutableArray.new;
for (NSInteger j = 0; j < endItem; j++) {
[indexPathes addObject:[NSIndexPath indexPathForItem:j inSection:0]];
}
[self.collectionView insertItemsAtIndexPaths:indexPathes];
[CATransaction setDisableActions:NO];
if (completion) {
completion(YES);
}
});
}