如何避免invalidateIntrinsicContentSize引起的无限循环

时间:2016-06-01 07:07:34

标签: ios autolayout

当视图放入tableviewcell时,此代码会导致无限循环。如何在不造成无限循环的情况下正确使用自动布局?

@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);
}

@end

0 个答案:

没有答案