I have created UICollectionView in storyboard and added header footer view its working fine.But My question is how to create UICollectionViewReusable view to add as SupplementaryView programatically.I tried but delegates not called.Please note that i have set delegate also.below code i have tried
- (void)setUpCustomCollectionView
{
self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 40, 320, 500) collectionViewLayout:layout];
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"brandingHeaderView"];
self.collectionView.bounces = NO;
self.collectionView.tag = 10;
self.collectionView.backgroundColor = [UIColor darkGrayColor];
[self.collectionView setDataSource:self];
[self.collectionView setDelegate:self];
self.collectionView.dataSource=self;
self.collectionView.delegate=self;
[self.baseScrollView addSubview:self.collectionView];
}
And in delegate
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
viewForSupplementaryElementOfKind:(NSString *)kind
atIndexPath:(NSIndexPath *)indexPath
{
if (kind == UICollectionElementKindSectionHeader) {
UICollectionReusableView *headerView = [self.collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"brandingHeaderView" forIndexPath:indexPath];
UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 80)];
view.backgroundColor = [UIColor redColor];
[headerView addSubview:view];
return headerView;
}
}
guide me.
In order to add header view programmatically to UICollectionView, you need to do following things.
I have just been having a similar issue where the following delegate wasn't being called...
Then I remembered that when I was defining an instance of the UICollectionViewFlowLayout, I had assigned the itemSize value as per following code...
Try also adding the following line to it as well for the header...
I guess mistake here:
UICollectionViewFlowLayout
can`t be header viewEdit:
To make it work you need subclass of
UICollectionReusableView
, don't forget overridereuseIdentifier
property. Also check docs:UICollectionReusableView Class Reference
to add it, a custom nib file should be created called Header(Header.xib) and UILabel is dragged from the object library and added to the Header.xib. A custom file a subclass of UICollectionReusableView is created next. e.g. HeaderCollectionReusableView.swift and the header.xib is made to see it and an IBOutlet of the label is done inside this custom class.