12

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

我的UICollectionViewCell每个只在他们的contentView有一个视图。这是我的一个自定义UIView子类,可以使用自动布局自动调整其大小以适合其所有子视图。它也正确实施了-intrinsicContentSize。然而,UICollectionView,或者说它的布局,似乎并不关心这一点。

我使用的是UICollectionViewFlowLayout,并尝试:

  • 离开itemSize其默认值。这使我的单元格大小为50 x 50.
  • 实施委托方法-collectionView:layout:sizeForItemAtIndexPath:。但是,当调用此方法时,单元格(显然)尚未出现在屏幕上,并且尚未由Auto Layout系统更新。

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

+0

原理相同http://stackoverflow.com/questions/18477220/have-uitableviewcell-resize-itself-with-autolayout/18481179#18481179,不幸的是,您需要预先给出尺寸。 – jrturton

+1

上面的作者在使用“自由”单元格时有一个评论 - 您创建一个然后保持周围,以填充并获取大小。你应该能够使用[单元systemLayoutSizeFittingSize:UILayoutFittingCompressedSize] - 我现在有问题,但其中的一个应该工作。 –

回答

-2

尝试的CollectionView:布局:sizeForItemAtIndexPath:

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { 
    return self.view.frame.size; 
} 
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。除此之外,这应该让你有

1

你有没有尝试过这样的:

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

,使约束的优先级(低= 250)

我认为,这个问题我们可以通过处理约束不变的替换。

相关问题