OStack程序员社区-中国程序员成长平台

标题: ios - Collectionview performBatchUpdates 崩溃 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 00:41
标题: ios - Collectionview performBatchUpdates 崩溃

我正在尝试使用 insertItemsAtIndexPaths 将新项目添加到我的 Collection View 中。我的应用在 performBatchupdate 时崩溃

- (void) addItems {
    NSArray *newProducts = @[@"1",@"2",@"3",@"4"];
    [self.collectionView performBatchUpdates:^{
        NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
        for (NSInteger index = self.array.count; index < (self.array.count + newProducts.count); index++) {
            [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]];
        }
        [self.array addObjectsFromArray:newProducts];
        [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
    }
                                  completion:nil];
}

以下是崩溃日志:

* Assertion failure in -[UICollectionView _createPreparedCellForItemAtIndexPath:withLayoutAttributes:applyAttributes:]

当单元格未向 Collection View 注册时,会发生此断言。我正在注册我的手机。



Best Answer-推荐答案


这对我有用: 如果 Collection View 为空,则重新加载,否则 insertItems。

- (void)addItems {

    NSArray *newProducts = @[@"1",@"2",@"3",@"4"];
    NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];

    for (NSInteger index = self.array.count; index < (self.array.count + newProducts.count); index++) {
        [arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]];
    }

    if (self.array) {
        [self.array addObjectsFromArray:newProducts];
        [self.collectionView performBatchUpdates:^{
            [self.collectionView insertItemsAtIndexPaths:arrayWithIndexPaths];
        }
                                      completion:nil];
    }
    else {
        self.array = [[NSMutableArray alloc] initWithArray:newProducts];
        [self.collectionView reloadData];

    }
}

关于ios - Collectionview performBatchUpdates 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25265183/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4