【问题标题】:Get the frame for a UICollectionView section获取 UICollectionView 部分的框架
【发布时间】:2016-06-03 13:56:56
【问题描述】:

如何在UICollectionView 实例中获取整个部分的框架(CGRect 值)? 我知道UITableView 有一个rectForSection: 方法。我正在为UICollectionView 寻找类似的东西。

我检查了UICollectionViewFlowLayout 的文档,但找不到任何类似于rectForSection: 的内容。

【问题讨论】:

标签: ios uicollectionview


【解决方案1】:

到collectionView添加类别

  @implementation UICollectionView (BMRect)

- (CGRect)bm_rectForSection:(NSInteger)section {
    NSInteger sectionNum = [self.dataSource collectionView:self numberOfItemsInSection:section];
    if (sectionNum <= 0) {
        return CGRectZero;
    } else {
        CGRect firstRect = [self bm_rectForRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:section]];
        CGRect lastRect = [self bm_rectForRowAtIndexPath:[NSIndexPath indexPathForItem:sectionNum-1 inSection:section]];
        return CGRectMake(0, CGRectGetMinY(firstRect), CGRectGetWidth(self.frame), CGRectGetMaxY(lastRect) - CGRectGetMidY(firstRect));
    }
}

- (CGRect)bm_rectForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self layoutAttributesForItemAtIndexPath:indexPath].frame;
}

@end

【讨论】:

  • 您的答案似乎全是代码。添加一些词语来描述问题所在和您的解决方案。
  • @idhong - 看起来您在将代码添加到帖子并使其格式正确时遇到了问题。要正确格式化代码,您需要在每行之前添加四个空格。您也可以粘贴代码,全选,然后在编辑器中按 CTRL-K 以自动为您执行此操作
【解决方案2】:

Collection view section frame依赖于collection view layout。它可能是流式布局或自定义布局。所以你不会得到任何预定义的解决方案。但是您可以使用

为您的布局计算它
UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForItemAtIndexPath:indexPath];

UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];

我会建议你继承 UICollectionViewLayout 并将你的节框架计算代码放在里面,这样你的节框架将永远是更新的。

注意:如果节起点和终点未垂直对齐,这些点不会给您 rect 的超集。老实说,没有更好的方法来获取节框架。

【讨论】:

  • 感谢您提供补充元素,即标题。很容易错过。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多