ios - 如何使 UICollectionViewCell 适合其 subview (使用自动布局)

标签 ios objective-c uicollectionview autolayout uicollectionviewcell

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

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

我正在使用 UICollectionViewFlowLayout,并尝试:

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

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

最佳答案

你试过这个吗:

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

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

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

关于ios - 如何使 UICollectionViewCell 适合其 subview (使用自动布局),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527084/

相关文章:

ios - 计算indexPath然后重新加载数据? swift 3

ios - 更新 NSarray 内特定键的值

ios - 如何使表格滚动工作 : UIControl within UITableView within UIControl

objective-c - 自定义 UITableViewCell + resignFirstResponder

ios - 将新单元格插入 Collection View

ios - 在 didSelectItemAt 中选择单元格时取消选择 cellForItemAt 中的单元格

iphone - 变换后获取帧值的最佳方法?

ios - 导入非常大的数据集时的CoreData和RestKit性能

ios - 注册远程通知在 Xcode 6 中不起作用

ios - ViewController 不启动