从 collectionViewCell 中删除 unknown/dynamic 个子视图的模式
Pattern for removing an unknown/dynamic number of subviews from collectionViewCell
我的应用程序有一个 collectionView,collectionViewCells 占据了整个屏幕。每个 collectionViewCell 都有一个背景视图和多个 "annotations"(视图)。我在 collectionViewCell 子类的方法中动态创建这些注释视图,因为每个单元格可能有不同数量的注释。
在collectionViewCell子类中,我在做
[self.contentView addSubview:annotationView];
对于每个注释视图。
我的问题是,当单元格出列并准备重新使用时,注释没有从单元格中删除,所以我最终导致多个单元格的注释显示不正确。
我知道我可以做类似的事情
[[[cell contentView] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
这是删除动态创建的子视图的最佳方法,还是有更好的方法?
由于您的单元格中有其他视图而不是动态视图,因此您需要一些比 cell.contentView.subviews
更好的方法来访问它们。我建议创建自定义 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
我的应用程序有一个 collectionView,collectionViewCells 占据了整个屏幕。每个 collectionViewCell 都有一个背景视图和多个 "annotations"(视图)。我在 collectionViewCell 子类的方法中动态创建这些注释视图,因为每个单元格可能有不同数量的注释。
在collectionViewCell子类中,我在做
[self.contentView addSubview:annotationView];
对于每个注释视图。
我的问题是,当单元格出列并准备重新使用时,注释没有从单元格中删除,所以我最终导致多个单元格的注释显示不正确。
我知道我可以做类似的事情
[[[cell contentView] subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];
这是删除动态创建的子视图的最佳方法,还是有更好的方法?
由于您的单元格中有其他视图而不是动态视图,因此您需要一些比 cell.contentView.subviews
更好的方法来访问它们。我建议创建自定义 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