I’m setting up my UICollectionView programmatically and everything looks right to me but when I test my app I get some really strange spacing, both vertically and horizontally. My LibraryViewController class, which sets up the collection view can be found here: LibaryViewController class. My LibraryCell init looks like this:
- (id)initWithFrame:(CGRect)frame
{
NSLog(@"Init called");
NSLog(@"%@", NSStringFromCGRect(frame));
self = [super initWithFrame:frame];
if (self) {
// Initialization code
imageView = [[UIImageView alloc] initWithFrame:frame];
[self.contentView addSubview:imageView];
}
return self;
}
So each time a cell is set up, I have it report to me what the frame is. The funny thing is these values look correct. Here is what part of my log file looks like that shows the frames are in the right place:
2012-12-12 11:08:48.333 ARApp2[16330:907] Init called
2012-12-12 11:08:48.335 ARApp2[16330:907] {{10, 10}, {80, 120}}
2012-12-12 11:08:48.341 ARApp2[16330:907] Loaded image0.png
2012-12-12 11:08:48.349 ARApp2[16330:907] success
2012-12-12 11:08:48.352 ARApp2[16330:907] Init called
2012-12-12 11:08:48.354 ARApp2[16330:907] {{120, 10}, {80, 120}}
2012-12-12 11:08:48.358 ARApp2[16330:907] Loaded image1.png
2012-12-12 11:08:48.365 ARApp2[16330:907] success
2012-12-12 11:08:48.368 ARApp2[16330:907] Init called
2012-12-12 11:08:48.370 ARApp2[16330:907] {{230, 10}, {80, 120}}
2012-12-12 11:08:48.375 ARApp2[16330:907] Loaded image2.png
2012-12-12 11:08:48.382 ARApp2[16330:907] success
But when you look at the result on the screen, it looks like this: Screenshot
This collection has four items in it. The first three are on the first row and so you can’t even see the third. Then the fourth one starts the next row but way lower than I would like. Can anyone see why these cells are spaced so far apart?
imageView = [[UIImageView alloc] initWithFrame:frame];This line seems to be your problem. Your image views are supposed to be {(0,0), (80,120)} but you’re assigning its superview’s frame as the image’s frame, so you wind up with the second image having a superview of {(120, 10), (80, 120)} but the image ALSO has the same offset and size, which is giving you crazy spacing.
tl;dr, set your imageView frame to self.bounds as your imageView should take up the entire superview.