iOS6 UICollecionView布局-水平布局-单元对齐

iOS6 UICollecionView布局-水平布局-单元对齐,ios6,uicollectionview,uicollectionviewcell,Ios6,Uicollectionview,Uicollectionviewcell,我有一个UICollectionViewFlowLayout,它基本上实现了我想要的功能,除了一件事——UICollectionViewCells在水平滚动并启用分页时的正确对齐 我基本上想要的是在多个页面上逐页滚动: 见下文第1节: 我的问题是,我有多个部分,总是使用相同的布局,但当我向右滚动时,它变为空(只有背景色),当我向后滚动到第一页(如上面的一页)时,我会得到一个奇怪的结果: 见第2条。在上面的链接中 显然,索引路径不知怎么搞混了——我真的不知道为什么 在本例中,My collect

我有一个UICollectionViewFlowLayout,它基本上实现了我想要的功能,除了一件事——UICollectionViewCells在水平滚动并启用分页时的正确对齐

我基本上想要的是在多个页面上逐页滚动:

见下文第1节:

我的问题是,我有多个部分,总是使用相同的布局,但当我向右滚动时,它变为空(只有背景色),当我向后滚动到第一页(如上面的一页)时,我会得到一个奇怪的结果:

见第2条。在上面的链接中

显然,索引路径不知怎么搞混了——我真的不知道为什么

在本例中,My collectionView:numberOfItemsInSection:方法始终返回“5”,My 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;
}
静态CGRect元素布局[]={
{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*)布局属性ForElementsInRect:(CGRect)rect{
NSArray*属性=[super-layouttributesforementsinrect:rect];
NSMutableArray*newAttributes=[NSMutableArray];
对于(int i=0;i<[属性计数];i++)
{
UICollectionViewLayoutAttribute*attrs=属性[i];
attrs.frame=元素布局[i];
[newAttributes addObject:attrs];
}
返回新属性;
}
但如果我没有子类化并尝试使用UICollectionViewFlowLayout中的标准委托调用,那么我会得到以下结果:

见3。在上面的链接中

这将正确地向右滚动,但布局错误。我所期望的是,具有nsindepath[0,1]的单元格将位于“大”单元格的右侧,而不是其下方。但即便如此,我仍需要将NSIndexPath[0,1]的单元格对齐,如图1所示


我在这里遗漏了什么吗?

经过许多麻烦之后,我终于明白了为什么布局表现得很奇怪

  • 当有多个部分时,需要将每个项的x原点rect更改为视图宽度的倍数

  • 更有趣的是:如果UICollectionViewFlowLayout生成的单元格比您预期的少,您可以覆盖UICollectionViewLayoutAttribute的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;
for(int i=0;i<(单元格计数);i++)
{
UICollectionViewLayoutAttribute*attrs=属性[i];
NSIndexPath*ExpectedIndexPath=[NSIndexPath indexPathForItem:i
分类:分段索引];
attrs.indexPath=expectedIndexPath;
attrs.frame=在绝对坐标中重新计算的帧;
[newAttributes addObject:attrs];
}
返回新属性;