Objective-c – UICollectionViewCell Padding

objective cuicollectionviewuicollectionviewcell

I am trying to set zero padding on collection view cells, I have set "Min Spacing" on the view controller to:

enter image description here

Yet it still has gaps between the cells:

enter image description here

Also I'd like it so that the cells wrap nicely depending on the width of the frame, for example each cell is 50px wide, so if there are six cells and I set the frame width to 150px, it will display two lines of three cells.

Yet if I set the frame width to 150 by doing:

- (void)viewDidLoad
{
    [super viewDidLoad];

    CGRect frame = self.collectionView.frame;
    frame.size.width = 150;
    self.collectionView.frame = frame;
}

It looks like in the above screen shot (too wide).

If I set it to something ridiculously small such as 10, it then wraps to some extent:

enter image description here

The UICollectionViewCell is set to 50 x 50:

enter image description here

I have also tried setting the size of the cell programatically, and also removed the UIEdgeInset:

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

I have disabled auto layout just incase that had any interference. Any advice as to how I can remove the padding and also have them wrap depending on the frame width / height?

Best Answer

You are using a UICollectionViewController which, like a UITableViewController, has the collection view (or table view) as the base view property of the view controller. This means it can't be resized from within the view controller; it's size is controlled by its superview - either the window, in this case, which has it as the root view controller, or a parent view controller if you were embedding it.

If you want to reduce the collection view area so the cells abut one another, you can amend the section insets of the collection view in the storyboard. In your case, an inset of 15 left and right brings the cells together - this is 9 * 50 (450) plus 30 = 480 which is the width of a 3.5inch iPhone in landscape.

Obviously this will be different in the iPhone 5 or iPad. You can either calculate the insets at run time, use a collection view held in a standard UIViewController subclass, or hold the UICollectionViewController as an embedded view controller. The latter two will enable you just to specify a size, which is probably nicer than calculating insets.

Related Topic