Adding a subview to a UICollectionViewCell that takes up entire cell frame
You should only interact with the cell's contentView
in this case.
UIView *menuItem = [UIView new];
menuItem.frame = cell.contentView.bounds;
menuItem.backgroundColor = [UIColor greenColor];
[cell.contentView addSubview:menuItem];
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
.