【问题标题】:iOS6 UICollecionViewFlowLayout - Horizontal layout - Alignment of cellsiOS6 UICollecionViewFlowLayout - 水平布局 - 单元格对齐
【发布时间】:2012-12-05 22:56:23
【问题描述】:

我有一个 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] 的单元格。

我错过了什么吗?

【问题讨论】:

    标签: ios6 uicollectionview uicollectionviewcell


    【解决方案1】:

    经过一番苦恼,我终于弄清楚了为什么布局表现得很奇怪。

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

    • 更有趣的是:如果 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;
    

    【讨论】:

      猜你喜欢
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 2013-10-03
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 2017-12-07
      • 1970-01-01
      相关资源
      最近更新 更多