Ios 用于从collectionViewCell中删除未知/动态数量的子视图的模式

Ios 用于从collectionViewCell中删除未知/动态数量的子视图的模式,ios,cocoa-touch,Ios,Cocoa Touch,我的应用程序有一个collectionView,其中collectionViewCells占据整个屏幕。每个collectionViewCell都有一个背景视图和多个注释视图。我在collectionViewCell子类的方法中动态创建这些注释视图,因为每个单元格的注释数量可能不同 在collectionViewCell子类中,我正在 [self.contentView addSubview:annotationView]; 对于每个注释视图 我的问题是,当单元格退出队列并准备重新使用时,注释

我的应用程序有一个collectionView,其中collectionViewCells占据整个屏幕。每个collectionViewCell都有一个背景视图和多个注释视图。我在collectionViewCell子类的方法中动态创建这些注释视图,因为每个单元格的注释数量可能不同

在collectionViewCell子类中,我正在

[self.contentView addSubview:annotationView];
对于每个注释视图

我的问题是,当单元格退出队列并准备重新使用时,注释没有从单元格中删除,因此我最终导致多个单元格的注释显示错误

我知道我可以做像这样的事情

[[[cell contentView] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

这是删除动态创建的子视图的最佳方法,还是有更好的方法?

由于单元格中有其他视图而不是动态视图,因此需要比cell.contentView.subview更好的方法来访问它们。我建议创建自定义UICollectionViewCell并创建用于操纵动态子视图的方法:

@interface CustomCell : UICollectionViewCell

- (void) addDynamicSubview:(UIView*)view;
- (void) removeAllDynamicSubviews;

@end

@implementation CustomCell {
    NSMutableArray* dynamicSubviews;
}

- (void) awakeFromNib {
    dynamicSubviews = [NSMutableArray new];
}

- (void) addDynamicSubview:(UIView*)view {
    [dynamicSubviews addObject:view];
    [self.contentView addSubview:view];
}

- (void) removeAllDynamicSubviews {
    [dynamicSubviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [dynamicSubviews removeAllObjects];
}

@end

谢谢,这是一个很好的方法。我在这个类中实现了-prepareforuse,并在那里调用了-removealldynamicsubview。