我正在使用UICollectionView创建网格视图,并希望通过分页滚动它。
现在我有一个问题。网格的偏移通过分页滚动逐渐移动。
我想让下一页单元格的左上角适合屏幕。
我的代码如下,
ViewController.m
- (void)loadView
{
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
self.view = [[GridView alloc] initWithLayout:layout];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationController.navigationBarHidden = YES;
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
GridView.m
#define GRID_SPACE (20)
- (id)initWithLayout:(UICollectionViewFlowLayout *)layout
{
self = [super initWithFrame:CGRectZero collectionViewLayout:layout];
if (self) {
self.pagingEnabled = YES;
self.backgroundColor = UIColor.redColor;
self.delegate = self;
self.dataSource = self;
[self registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([UICollectionViewCell class])];
}
return self;
}
#pragma mark -
#pragma mark UICollectionViewDelegate
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize selfSize = self.frame.size;
return CGSizeMake( (selfSize.width - GRID_SPACE) / 2, (selfSize.height - GRID_SPACE) / 2 );
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
return GRID_SPACE;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
return GRID_SPACE;
}
如果你能给我一个很好的解决方案,我将不胜感激。
谢谢。
UIScrollView(UICollectionView继承自的)的页面大小是其视口的大小,因此要使其工作,您需要在顶部包含红色边框的高度。如果您不想在顶部或底部显示边框,则可以将UICollectionView拉伸到另一个元素下方或显示顶部下方(如果它在顶部对齐)。
LGP的答案解决了我的问题。我添加到GridView.m中的已解决代码如下,
将网格项的长度添加到CollectionView的高度,因为theight是Paging Scroll的长度。而且,您需要将网格项的长度设置为CollectionView insets的底部。
在GridView.m中
- (void)layoutSubviews
{
[super layoutSubviews];
CGSize parentSize = self.superview.frame.size;
self.frame = CGRectMake(0, 0, parentSize.width, parentSize.height + GRID_SPACE);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(0, 0, GRID_SPACE, 0);
}