【问题标题】:How to make UICollectionViewCell fit its subviews (using Auto Layout)如何使 UICollectionViewCell 适合其子视图(使用自动布局)
【发布时间】:2013-09-02 20:08:56
【问题描述】:

如何使用自动布局根据其子视图的大小更改UICollectionViewCell 的大小?

我的UICollectionViewCells 每个人的contentView 中只有一个视图。这是我的一个自定义UIView 子类,它使用自动布局自动调整自身大小以适应其所有子视图。它还正确实现了-intrinsicContentSize。然而UICollectionView,或者更确切地说是它的布局,似乎并不关心这个。

我正在使用UICollectionViewFlowLayout,并尝试过:

  • itemSize 保留为其默认值。这给了我大小为 50 x 50 的单元格。
  • 实现委托方法-collectionView:layout:sizeForItemAtIndexPath:。但是,当调用此方法时,单元格(显然)还没有出现在屏幕上,也没有被自动布局系统更新。

有什么方法可以使用标准 Apple 类根据子视图更改单元格的大小?还是我必须实现我自己的UICollectionViewLayout 子类或其他什么?

【问题讨论】:

  • 原理和stackoverflow.com/questions/18477220/…一样,可惜要先给出尺寸。
  • 上述作者有一个关于使用“免费”单元格的评论 - 您创建然后保留的单元格,填充然后获取大小。您应该可以使用 [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize] - 我现在遇到了问题,但其中一个应该可以工作。

标签: ios objective-c uicollectionview autolayout uicollectionviewcell


【解决方案1】:

试试 collectionView:layout:sizeForItemAtIndexPath:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
     return self.view.frame.size;
}

【讨论】:

    【解决方案2】:

    我用过

    - (void)collectionView:(UICollectionView *)collectionView willDisplayCell:(UICollectionViewCell *)cell forItemAtIndexPath:(NSIndexPath *)indexPath {
    
        if (indexPath.row == 0) {
            UIButton *button = (UIButton *)[cell viewWithTag:2];
            CGRect frame = cell.frame;
            frame.size.width = button.frame.size.width;
            cell.frame = frame;
        }
    
    }
    

    并且能够根据小测试应用中按钮子视图的宽度调整单元格的大小。

    确保子视图上的标签大于 0,因为如果使用 0,它只会返回 contentView。除此之外,这应该可以让您到达那里

    【讨论】:

      【解决方案3】:

      你试过了吗:

      [self.view layoutIfNeeded];
      [UIView animateWithDuration:0.5 animations:^{
           constraintConstantForWidth.constant = subviews.size.width;
           constraintConstantForHeight.constant = subviews.size.height;
           [self.view layoutIfNeeded];
      }];
      

      并使约束的优先级(low = 250)

      我认为这个问题我们可以通过约束常量替换来处理。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-13
        • 1970-01-01
        • 2014-07-06
        • 2013-08-06
        • 2015-04-14
        • 1970-01-01
        相关资源
        最近更新 更多