I have an UIViewController which contains a UICollectionView. But the UICollectionView does not fill all the UIViewController.
I find that there is space whose height equals the height of NavigationBar between the cell and the top edge of the UICollectionView. I don't know how I can set the cell position to (0,0) in the UICollectionView. (like this, the space is in the red rectangle)
I found this link How do I set the position of a UICollectionViewCell? And I subclass UICollectionViewFlowLayout (the following are my code)
MZMCollectionViewFlowLayout.h
#import <UIKit/UIKit.h>
@interface MZMCollectionViewFlowLayout : UICollectionViewFlowLayout
@end
MZMCollectionViewFlowLayout.m
#import "MZMCollectionViewFlowLayout.h"
@implementation MZMCollectionViewFlowLayout
- (CGSize)collectionViewContentSize
{
return [super collectionViewContentSize];
}
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
return [super layoutAttributesForElementsInRect:rect];
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(@"MZMCollectionViewFlowLayout layoutAttributesForItemAtIndexPath");
if (indexPath.section == 0 && indexPath.row == 1) // or whatever specific item you're trying to override
{
UICollectionViewLayoutAttributes *layoutAttributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
layoutAttributes.frame = CGRectMake(0,0,100,100); // or whatever...
return layoutAttributes;
}
else
{
return [super layoutAttributesForItemAtIndexPath:indexPath];
}
}
@end
and using it like this:
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// hide the tool bar
[self.navigationController setToolbarHidden:YES animated:YES];
// set title
self.navigationItem.title = @"User Album";
[self.userAlbumView setCollectionViewLayout:[[MZMCollectionViewFlowLayout alloc] init]];
}
But it does not work. The log NSLog(@"MZMCollectionViewFlowLayout layoutAttributesForItemAtIndexPath"); doesn't show. And the blank is still there.
Thanks for any help!
FYI, this is answered more correctly here: UICollectionView adds top margin
The problem is the view controller is automatically adjusting scroll view insets. That can be turned off either in code or IB. In code just set:
self.automaticallyAdjustsScrollViewInsets = NO;