我正在使用 UICollectionView
构建马赛克 View 。
我已将 UICollectionViewFlowLayout
子类化以布置一个可以水平和垂直滚动 的固定网格。我还附上了一个 UIPinchGestureRecognizer
,这样集合就可以缩放/缩放。
集合中的每个单元格都包含一个具有一定透明度的 UIImage
。我想添加一个将随单元格一起滚动和缩放的背景图像。
我尝试了多种不同的解决方案。
- 使用
colorWithPatternImage
设置UICollectionView
的背景颜色。 (不随内容滚动/调整大小) - 将每个单元格的背景 ImageView 设置为背景图像的相关裁剪部分。 (占用太多内存)
我一直在研究 Supplementary 和 Decoration Views,但一直在努力解决这个问题。我想我需要使用 Supplementary View ,因为背景中使用的图像会根据 datasource
发生变化。
我不明白的是如何只注册一个补充 View 来跨越整个 collectionview
的宽度和高度。它们似乎与 indexPath
相关联,即每个单元格。
最佳答案
不知道您是否找到了答案...!
您希望使用补充 View ,方向正确。补充 View 的索引路径不绑定(bind)到单元格,它有自己的索引路径。
然后在 UICollectionViewFlowLayout
的子类中,您需要子类化一些方法。 docs很不错!
在layoutAttributesForElementsInRect:
您需要调用 super 的方法,然后为补充 View 添加另一组布局属性。
然后在layoutAttributesForSupplementaryViewOfKind:atIndexPath:
方法将返回属性的大小设置为 Collection View 内容的大小,以便图像填充所有内容,而不仅仅是框架。您可能还想将 z 顺序设置为,以确保它位于单元格后面。请参阅 UICollectionViewLayoutAttributes 的文档
@implementation CustomFlowLayout
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSMutableArray *attributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
// Use your own index path and kind here
UICollectionViewLayoutAttributes *backgroundLayoutAttributes = [self layoutAttributesForSupplementaryViewOfKind:@"background" atIndexPath:[NSIndexPath indexPathWithItem:0 inSection:0]];
[attributes addObject:backgroundLayoutAttributes];
return [attributes copy];
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
if ([kind isEqualToString:@"background"]) {
UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:kind withIndexPath:indexPath];
attrs.size = [self collectionViewContentSize];
attrs.zIndex = -10;
return attrs;
} else {
return [super layoutAttributesForSupplementaryViewOfKind:kind atIndexPath:indexPath];
}
}
@end
在您的 Collection View 数据源中,您需要此方法:
collectionView:viewForSupplementaryElementOfKind:atIndexPath:
-(void)viewDidLoad
{
[super viewDidLoad];
// Setup your collection view
UICollectionView *collectionView = [UICollectionView initWithFrame:self.view.bounds collectionViewLayout:[CustomFlowLayout new]];
[collectionView registerClass:[BackgroundReusableView class] forSupplementaryViewOfKind:@"background" withReuseIdentifier:@"backgroundView"];
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if ([kind isEqualToString:@"background"]) {
BackgroundReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"backgroundView" forIndexPath:indexPath];
// Set extra info
return view;
} else {
// Shouldn't be called
return nil;
}
}
希望所有这些都能让您走上正轨:)
关于ios - 如何将背景图像添加到将滚动和缩放单元格的 UICollectionView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21161823/