在特殊情况下,intrinsicContentSize会导致无限循环
我做了一个容器视图,我打电话给SimpleStackView。 这个想法很简单,任何子视图都堆叠在彼此之上。 SimpleStackView的宽度决定了其子视图的宽度,而SimpleStackView的高度则由其子视图的高度决定。
我在layoutSubviews中调用了每个子视图上的sizeThatFits,并使用返回的高度将它们布置在eachother之上。 这些高度的总和还决定了从SimpleStackView的sizeThatFits覆盖和intrinsicContentSize覆盖返回的内容。
我支持iOS 7,所以我不能使用UIStackView。
我使用AutoLayout来布局我的应用程序中的大部分东西。 我的SimpleStackView在许多地方工作正常,其布局使用AutoLayout旁边的其他视图(我依靠它的intrinsicContentSize来定义它的高度,没有高度约束),除了一个SimpleStackView被放在一个UITableViewCell的contentView中的一个UITableView的。 在这种情况下,会触发一个无限循环。 我不是一个AutoLayout的专家。 我可能会错过在AutoLayout内部如何使用intrinsicContetSizes? 这可能是什么情况? 我如何正确使用intrinsicContentSize,使其在所有情况下都能正常工作?
SimpleStackView的代码相对较短; 这里是完整的类实现:
@implementation SimpleStackView @synthesize rowSpacing=_rowSpacing; - (void)layoutSubviews { [super layoutSubviews]; [self sizeToFit]; [self invalidateIntrinsicContentSize]; CGFloat nextRowTop = 0; for (UIView *view in self.subviews) { CGSize size = [view sizeThatFits:CGSizeMake(self.bounds.size.width, view.bounds.size.height)]; view.frame = CGRectMake(0, nextRowTop, self.bounds.size.width, size.height); nextRowTop += view.frame.size.height + self.rowSpacing; } } - (CGSize)sizeThatFits:(CGSize)size { CGFloat sumOfHeights = 0; for (UIView *view in self.subviews) { sumOfHeights += [view sizeThatFits:CGSizeMake(size.width, view.bounds.size.height)].height; } CGFloat sumOfRowSpacings = MAX(0, (int)self.subviews.count - 1) * self.rowSpacing; return CGSizeMake(size.width, sumOfHeights + sumOfRowSpacings); } - (CGSize)intrinsicContentSize { CGFloat intrinsicHeight = [self sizeThatFits:self.bounds.size].height; return CGSizeMake(UIViewNoIntrinsicMetric, intrinsicHeight); } // i tried this to fix the infinite loop; didnt work was still stuck in infinite loop //- (void)setFrame:(CGRect)frame //{ // CGRect frameBefore = self.frame; // [super setFrame:frame]; // if (NO == CGRectEqualToRect(frameBefore, frame)) // [self invalidateIntrinsicContentSize]; //} @end
编辑:我忘了提及; 导致无限循环的UITableCellView从contentView的顶部到contentView的底部都有一个不间断的约束链。 无限循环停止发生,当我删除一个约束打破链。 我想保持约束,他们在那里压缩多行UILabel当行高度很小(这是在UITableViewDelegate的heightForRowAtIndexPath中设置)。
- 在UICollectionView上animation自动布局约束更改
- 带dynamictypes标签的AutoLayoutdynamicUITableView单元格高度
- 自动布局+ UIScrollView和单个子视图
- AutoLayoutdynamic.xib视图高度
- 正确地使用Interface Builder和Autolayout在UIScrollView中调整UILabel的大小?
- 使用AutoLayout(Storyboard)自动调整UIView的高度到它的子视图
- UIScrollView和自动布局不工作
- UIView长宽比混淆了systemLayoutSizeFittingSize
- 如何使方形视图调整其超视图使用自动布局