如何使用自动布局使UICollectionViewCell适应其子视图?

12

如何使用自动布局基于子视图的大小更改UICollectionViewCell的大小?

我的每个UICollectionViewCell只有一个视图作为其contentView的子视图。这是我自己的自定义UIView子类,它使用自动布局自动调整大小以适应所有子视图。它还正确实现了-intrinsicContentSize方法。然而,UICollectionView或者说它的布局似乎并不关心这些。

我正在使用UICollectionViewFlowLayout并尝试了以下操作:

  • 保留itemSize使用默认值。这会给我50 x 50大小的单元格。
  • 实现委托方法-collectionView:layout:sizeForItemAtIndexPath:。然而,当该方法被调用时,单元格(显然)还没有出现在屏幕上,并且尚未由自动布局系统更新。

是否有一种方法可以使用标准的Apple类来基于它们的子视图更改单元格的大小?还是我必须实现自己的UICollectionViewLayout子类或其他什么东西?


与 https://dev59.com/THbZa4cB1Zd3GeqPCy4o#18481179 相同的原则,不幸的是,您需要提前给出大小。 - jrturton
1
以上作者在那里评论了使用“自由”单元格的问题 - 您创建并保留一个单元格,以填充并获取其大小。您应该能够使用[cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize] - 我现在遇到了一些问题,但其中一个应该可以工作。 - David H
3个回答

1
你尝试过这个吗:

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

并将约束条件的优先级设为低(low = 250)

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


0

我使用了

- (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。除此之外,这应该可以帮助您实现目标。


-2

尝试使用collectionView:layout:sizeForItemAtIndexPath:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接