Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView decoration in empty collection view

I've implemented an UICollectionView with a custom layout. It adds a decoration view to the layout. I use the following code to add layout attributes of the decoration view:

-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *allAttributes = [super layoutAttributesForElementsInRect:rect];
    return [allAttributes arrayByAddingObject:[self layoutAttributesForDecorationViewOfKind:kHeaderKind atIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]]];
}

The data in the collection view is provided by a NSFetchedResultsController.

Now it looked likes it worked fine, but when the collection view is empty, it fails because there's section 0. Tried to use it without an index path, but fails too. Any thoughts on how to use decoration views in an empty UICollectionView? Should be possible since decoration views aren't data-driven.

like image 761
Guido Hendriks Avatar asked Oct 12 '12 13:10

Guido Hendriks


1 Answers

When using a decoration view or a supplemental view not attached to a specific cell, use [NSIndexPath indexPathWithIndex:] to specify the index path. Here is a sample code:

@interface BBCollectionViewLayout : UICollectionViewFlowLayout

@end

@implementation BBCollectionViewLayout

- (void)BBCollectionViewLayout_commonInit {
    [self registerClass:[BBCollectionReusableView class] forDecorationViewOfKind:BBCollectionReusableViewKind];
}

- (id)initWithCoder:(NSCoder *)aDecoder {
    if ((self = [super initWithCoder:aDecoder])) {
        [self BBCollectionViewLayout_commonInit];
    }
    return self;
}

- (id)init {
    self = [super init];
    if (self) {
        [self BBCollectionViewLayout_commonInit];
    }
    return self;
}

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSMutableArray *array = [NSMutableArray arrayWithArray:[super layoutAttributesForElementsInRect:rect]];

    UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForDecorationViewOfKind:BBCollectionReusableViewKind atIndexPath:[NSIndexPath indexPathWithIndex:0]];

    if (CGRectIntersectsRect(rect, attributes.frame)) {
        [array addObject:attributes];
    }

    return array;
}

- (UICollectionViewLayoutAttributes *)layoutAttributesForDecorationViewOfKind:(NSString*)elementKind atIndexPath:(NSIndexPath *)indexPath {
    UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForDecorationViewOfKind:elementKind withIndexPath:indexPath];
    attributes.frame = CGRectMake(0., 60., 44., 44.);
    return attributes;
}

@end
like image 180
Benoît Avatar answered Nov 14 '22 03:11

Benoît