Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a subview to a UICollectionViewCell that takes up entire cell frame

I am trying to simply add a UIView to a UICollectionViewCell that takes up the entire cell's frame. The code I have now only displays a single cell in the top left corner (I suspect each cell is getting layer out on top of each other). How exactly can I do this?

I plan on subclassing UIView later so as to customize the view that I am adding to the cell. I don't want to subclass UICollectionViewCell however based on the way I will be using it.

#pragma mark - Collection view data source

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 6;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];

    UIView *menuItem = [[UIView alloc] init];
    menuItem.frame = cell.frame;
    menuItem.backgroundColor = [UIColor greenColor];
    [cell addSubview:menuItem];

    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath; {
    return CGSizeMake(60, 60);
}
like image 868
DBoyer Avatar asked Jan 04 '14 22:01

DBoyer


1 Answers

You'll need to use bounds, not frame. If you don't know the difference between the two or why this matters, you should read up on this and get comfortable with it before going further:

menuItem.frame = cell.bounds;

You'll also want to set an autoresizing mask, since the cell won't initially be at the correct size:

menuItem.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

And, really, you should be adding this to the cell's contentView property:

[cell.contentView addSubview:menuItem];
menuItem.frame = cell.contentView.bounds;

That said, if you plan on adding lots of subviews to menuItem, I recommend subclassing UICollectionViewCell instead of trying to build it in your cellForItemAtIndexPath: method. It will be much easier to control if the layout and setup is encapsulated in a different class, and you can respond to height / width changes by overriding layoutSubviews.

like image 89
Aaron Brager Avatar answered Sep 20 '22 18:09

Aaron Brager