【发布时间】:2018-02-09 09:03:52
【问题描述】:
在我的datasource 中动态插入对象时,我遇到了一种可以理解的行为。
这是我的代码:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
[_dataSource insertObject:newObject atIndex:indexPath.row];
[_collectionView insertItemsAtIndexPaths:@[indexPath]];
我在这里做的是在我的datasource 中插入一个对象(因为这个对象在启动时还没有准备好,我通过delegate 方法接收它)。
然后,我想在这个特定的 indexPath 处触发我的cellForRow,以便创建和插入适当的单元格。
这里的问题是它短暂地显示了单元格的上一个 内容。
即使我在我的自定义 UICollectionViewCell 类中得到了这个:
override func prepareForReuse() {
super.prepareForReuse()
self.mediaContainer = nil
self.outletTitle.text = ""
self.outletImage.image = nil
self.outletButtonAction = nil
self.bottomView = nil
}
我是否以错误的方式使用prepareForReuse?
我应该在插入之前致电reloadItemsAtIndexPath 吗?
这是我的 cellForRow :
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Object *object = [_datasource objectAtIndex:indexPath.row];
UICollectionViewCell *cell = nil;
switch (object.type.intValue) {
case CELLTYPE1... :
// specific cases for specific cell type
.
.
.
case CELLTYPE2:
{
static BOOL nibMyCellloaded = NO;
if (!nibMyCellloaded) {
UINib *nib = [UINib nibWithNibName:@"CustomCollectionViewCell" bundle:nil];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:@"reuseId"];
}
CustomCollectionViewCell* customCell = (CustomCollectionViewCell*)[self.collectionView dequeueReusableCellWithReuseIdentifier:@"reuseId" forIndexPath:indexPath];
[customCell updateCellOutletWith:_customView vc:self];
cell = customCell;
break;
return cell;
}
【问题讨论】:
-
在
cellForItemAt使用dequeueReusableCell(withReuseIdentifier: cell, for: indexPath)并使用reloadItemsAtIndexPath -
在
prepareForReuse中放置一个断点。另外,尝试使用performBatchUpdates添加新项目。 -
我认为你应该先在数组中插入项目而不是 reloadItemsAtIndexPath。稍后处理要显示的内容或处理对 cellforrow 进行检查的 celldeque 问题。
-
显示您的
cellForItemAtIndexPath代码
标签: ios objective-c uicollectionview uicollectionviewcell