Title: weird position uicollectionview header section xcode
Tags: ios;objective-c;cocoa-touch;uicollectionview
Question: I don't know why but for the even numbered sections of my UICollectionView, the header is misplaced.
It is, however, correct for the odd numbered sections.
Here is my code :
#import "ExosViewController.h"
#import "ExCell.h"
#import "ExerciseDatabase.h"
#import "Exercise.h"
#import "HeaderView.h"
@implementation ExosViewController
@synthesize backgroundImage;
@synthesize titles;
@synthesize subtitles;
@synthesize enonces;
@synthesize numbers;
@synthesize parts;
NSInteger nbItemsInPart[7];
int item =0;
int nbSections = -1;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
return self;
- (void)viewDidLoad
[super viewDidLoad];
[self setBackground];
[self setBarPreferences];
[self loadData];
[self addCollView];
- (void)setBackground
self.backgroundImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fond.png"]];
self.backgroundImage.frame = self.view.bounds;
self.backgroundImage.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
self.backgroundImage.contentMode = UIViewContentModeScaleAspectFill;
[self.view addSubview:self.backgroundImage];
[self.view sendSubviewToBack:self.backgroundImage];
- (void)setBarPreferences
UIColor *color = [UIColor colorWithRed:209.0/255.0 green:8.0/255.0 blue:109.0/255.0 alpha:1];
self.navigationController.navigationBar.tintColor = color;
-(void)addCollView
[collectionView setDataSource:self];
[collectionView setDelegate:self];
// Configure layout
UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout*)collectionView.collectionViewLayout;;
[flowLayout setItemSize:CGSizeMake(762, 112)];
[flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
flowLayout.minimumInteritemSpacing = 1000.0f;
flowLayout.minimumLineSpacing = 0.0f;
flowLayout.sectionInset = UIEdgeInsetsMake(20, 0, 20, 0);
flowLayout.headerReferenceSize = flowLayout.itemSize;
[collectionView setCollectionViewLayout:flowLayout];
[collectionView setBackgroundColor:[UIColor clearColor]];
[collectionView registerClass:[ExCell class] forCellWithReuseIdentifier:@"ExCell"];
[collectionView registerClass:[HeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView"];
[self.view addSubview:collectionView];
- (void)loadData
ExerciseDatabase *database = [[ExerciseDatabase alloc ] init];
NSArray *exerciseInfos = database.exerciseInfos;
titles = [[NSMutableArray alloc]init];
enonces = [[NSMutableArray alloc]init];
subtitles = [[NSMutableArray alloc]init];
parts = [[NSMutableArray alloc]init];
numbers = [[NSMutableArray alloc]init];
int n=1;
nbSections =-1;
for (Exercise *exercise in exerciseInfos) {
[titles addObject:exercise.title];
[numbers addObject:[NSString stringWithFormat:@"%d",exercise.num]];
[subtitles addObject:exercise.subtitle];
[enonces addObject:exercise.enonce];
NSArray *partsArray = [parts copy];
if(![partsArray containsObject:exercise.header]) {
[parts addObject:exercise.header];
nbSections++;
n = 1;
} else {
n++;
}
nbItemsInPart[nbSections] = n;
#pragma mark - UICollectionView Datasource
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section
//section commence à 0.
NSLog(@"%ld",nbItemsInPart[section]);
return nbItemsInPart[section];
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView
return (nbSections+1);
// creates the individual cells to go in the menu view
- (ExCell*) collectionView:(UICollectionView *)collectView cellForItemAtIndexPath:(NSIndexPath *)indexPath
//create collection view cell
ExCell *cell = (ExCell *)[collectView dequeueReusableCellWithReuseIdentifier:@"ExCell" forIndexPath:indexPath];
// the index is the row number in section + the number of items in all previous sections
int index = (int)indexPath.row;
for(int k=0; k < indexPath.section ; k++) {
index += nbItemsInPart[k];
//configure cell :
NSMutableString *text = [[NSMutableString alloc]initWithString:@"Practical Exercise "];
[text appendString:[NSString stringWithFormat:@"%d",index+1]];
[text appendString:@"\n"];
[text appendString:[titles objectAtIndex:index]];
cell.label.text = text;
[cell.reminder addTarget:self action:@selector(doSomething:) forControlEvents: UIControlEventTouchUpInside];
[cell.done addTarget:self action:@selector(checked:) forControlEvents:UIControlEventTouchUpInside];
// set tag to the indexPath.row so we can access it later
[cell setTag:index];
// return the cell
return cell;
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
HeaderView *headerView = [collectView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];
NSMutableString *text = [[NSMutableString alloc]initWithString:@" "];
[text appendString:[parts objectAtIndex:indexPath.section]];
headerView.label.text = text;
return headerView;
-(IBAction)doSomething:(id) sender
[self performSegueWithIdentifier:@"reminder" sender:self];
-(void)checked:(id)sender
if([sender imageForState:UIControlStateNormal] == [UIImage imageNamed:@"checked.png"]) {
[sender setImage:[UIImage imageNamed:@"unchecked.png"] forState:UIControlStateNormal];
} else {
[sender setImage:[UIImage imageNamed:@"checked.png"] forState:UIControlStateNormal];
and here is the code of my custom header cell :
#import "HeaderView.h"
@implementation HeaderView
- (id)initWithFrame:(CGRect)frame
self = [super initWithFrame:frame];
if (self) {
self.label = [[UILabel alloc] initWithFrame:self.frame];
NSLog(@"created label");
self.label.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.5];
[self addSubview:self.label];
return self;
Looks like:

Here is the accepted answer: Instead of using self.frame as the initial frame use self.bounds
- (id)initWithFrame:(CGRect)frame
self = [super initWithFrame:frame];
if (self) {
self.label = [[UILabel alloc] initWithFrame:self.bounds];
NSLog(@"created label");
self.label.backgroundColor = [UIColor colorWithWhite:0.2 alpha:0.5];
[self addSubview:self.label];
return self;


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:03/13/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<ios><objective-c><cocoa-touch><uicollectionview>', 'Title': 'weird position uicollectionview header section xcode', 'ViewCount': 1234, 'id': 22387331, 'user_AboutMe': '', 'user_AccountId': 4168234.0, 'user_DisplayName': 'Stoli', 'user_Reputation': 69.0, 'user_Views': 40.0, 'user_id': 3416704.0}}