th3*_*ler 6 objective-c ios uicollectionview uicollectionviewlayout
我正在使用构建马赛克视图UICollectionView.
我已经子类化UICollectionViewFlowLayout了一个可以水平和垂直滚动的固定网格.我也附上了一个UIPinchGestureRecognizer这样的集合可以缩放/缩放.
集合中的每个单元格都包含UIImage一些透明度.我想添加一个背景图像,用于滚动和缩放单元格.
我尝试了许多不同的解决方案.
UICollectionView使用colorWithPatternImage.(不会滚动/调整内容大小)我一直在寻找补充和装饰视图,但努力让我的头围绕它.我想我需要使用补充视图,因为后台使用的图像会根据不同而改变datasource.
我不明白的是我如何只注册一个补充视图来跨越整体的宽度和高度collectionview.它们似乎与indexPath每个细胞相关联.
不知道你找到答案了吗...!
您想要使用补充视图的方向是正确的。补充视图的索引路径不绑定到单元格,它有自己的索引路径。
然后,在您的子类中,UICollectionViewFlowLayout您需要对一些方法进行子类化。文档非常好!
在该layoutAttributesForElementsInRect:方法中,您需要调用 super,然后为补充视图添加另一组布局属性。
然后在该layoutAttributesForSupplementaryViewOfKind:atIndexPath:方法中,将返回属性的大小设置为集合视图内容的大小,以便图像填充所有内容,而不仅仅是框架。您可能还想将 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
Run Code Online (Sandbox Code Playgroud)
在您的集合视图数据源中,您需要此方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
希望所有这些都能让您走上正轨:)