我创建并测试了这个简单的示例,它似乎在所有可能的情况下都可以在 iOS 7 中使用(0 个部分,1 个包含 0 个项目的部分等)。这是我的布局类,它的子类UICollectionViewFlowLayout
。该项目的其余部分只是脚手架。
#import "JKLayout.h"
#import "JKDecoration.h"
@implementation JKLayout
- (instancetype)init
{
if (self = [super init]) {
[self registerClass:[JKDecoration class] forDecorationViewOfKind:@"Decoration"];
}
return self;
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *allAttributes = [super layoutAttributesForElementsInRect:rect];
// It’s important to set indexPath to nil. If I had set it to indexPath 0-0, it crashed with InternalInconsistencyException
// because I was trying to get decoration view for section 0 while there in reality was no section 0
// I guess if you need to have several decoration views in this case, you’d identify them with a method other than indexpath
return [allAttributes arrayByAddingObject:[self layoutAttributesForDecorationViewOfKind:@"Decoration" atIndexPath:nil]];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString *)decorationViewKind atIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *attr = [super layoutAttributesForDecorationViewOfKind:decorationViewKind atIndexPath:indexPath];
if (!attr) {
attr = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:decorationViewKind withIndexPath:indexPath];
attr.frame = CGRectMake(0, 200, 100, 100);
}
return attr;
}
@end