我有一个基本上做我想要的UICollectionViewFlowLayout,除了一件事 - UICollectionViewCells正确对齐,当它水平滚动并启用分页时。
我基本上想要的是 - 在多个页面上逐页滚动:
见这里的1: UICollectionView Pictures
我的问题是,我有多个部分,总是使用相同的布局,但是当我向右滚动时,它变空(只是背景颜色),当我滚动回到第一页(如上面的那个) )我得到一个奇怪的结果:
见上面链接中的2.
显然索引路径混淆了 - 我真的不知道为什么。
我的collectionView:numberOfItemsInSection:方法总是返回“5”,而我的numberOfSectionsInCollectionView:在这个例子中返回“2”。我已经将UICollectionViewFlowLayout子类化为:
static CGRect elementLayout[] = {
{20, 20, 649.333333, 294},
{20, 334, 314.666666, 294},
{688, 20.0, 314.666666, 294},
{354.666666, 334, 314.666666, 294},
{688, 334, 314.666666, 294},
};
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
NSMutableArray *newAttributes = [NSMutableArray array];
for(int i = 0; i < [attributes count]; i++)
{
UICollectionViewLayoutAttributes* attrs = attributes[i];
attrs.frame = elementLayout[i];
[newAttributes addObject:attrs];
}
return newAttributes;
}
但是,如果我没有子类并尝试使用UICollectionViewFlowLayout的标准委托调用,那么我得到这个:
参见上面链接中的3.
这向右滚动,但布局错误。我所期望的是,具有NSIndexPath [0,1]的单元格将位于“大”单元格的右侧,而不是位于“大”单元格的右侧。但即便如此,我还是需要将NSIndexPath [0,1]的单元格与图片1对齐。
我在这里错过了什么吗?
答案 0 :(得分:0)
经过很多麻烦我终于想通了,为什么布局表现得很奇怪。
当有多个部分时,您需要将每个项目的x-origin更改为视图宽度的倍数。
更有趣的是:如果UICollectionViewFlowLayout生成的单元格少于预期,则可以覆盖UICollectionViewLayoutAttributes的indexPath,以匹配预期的布局。
所以工作配置是:
for(int i = 0; i < (countOfCellsAnticipated); i++)
{
UICollectionViewLayoutAttributes* attrs = attributes[i];
NSIndexPath* anticipatedIndexPath = [NSIndexPath indexPathForItem:i
inSection:sectionIndex];
attrs.indexPath = anticipatedIndexPath;
attrs.frame = recalculatedFrameInAbsoluteViewCoordinates;
[newAttributes addObject:attrs];
}
return newAttributes;