自从iOS 8以来,[UICollectionViewCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]
返回的高度为0。
以下是代码的作用:
在iOS 7中,为了确定UICollectionView
中单元格的大小,我使用了xib文件中基于自动布局的单元格上的systemLayoutSizeFittingSize:
。这个大小取决于在我的xib文件中作为UICollectionViewCell
子视图的UILabel
的字体大小。标签的字体设置为UIFontTextStyleBody
。因此,基本上单元格的大小取决于在iOS 7中进行的字体大小设置。
以下是代码本身:
+ (CGSize)cellSize {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([MyCollectionViewCell class]) bundle:nil];
// Assumption: The XIB file only contains a single root UIView.
UIView *rootView = [[nib instantiateWithOwner:nil options:nil] lastObject];
if ([rootView isKindOfClass:[MyCollectionViewCell class]]) {
MyCollectionViewCell *sampleCell = (MyCollectionViewCell*)rootView;
sampleCell.label.text = @"foo"; // sample text without bar
[sampleCell setNeedsLayout];
[sampleCell layoutIfNeeded];
return [sampleCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
}
return CGSizeZero;
}
在iOS 7中它完美运作,但在iOS 8中却不行。很遗憾,我不知道为什么。
如何在iOS 8中获得UICollectionViewCells的自动布局大小?
PS:使用
return [sampleCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
取代
return [sampleCell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
就像有些人可能会建议的那样,这没有任何区别。