2

This code causes an infinite loop when the view is put insida a tableviewcell. How do i use autolayout correctly without causing an infinite loop here?

@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
quad16
  • 184
  • 5
  • 20
  • If you are using auto layout properly you shouldn't have to do any of that. I'd recommend reading some documentation / tutorials about auto layout. Also, the @implementation at the top of the code says SimpleStackView. If you are using a UIStackView you DEFINITELY shouldn't be doing any of that. – GCBenson Jun 01 '16 at 16:13
  • Thanks for writing to me. The reason i have this SimpleStackView class is that i support iOS 7 so cant use UIStackView. SimpleStackView is just a direct UIView subclass. I posted [this more detailed question](http://stackoverflow.com/questions/37541319/intrinsiccontentsize-causes-infinite-loop-in-special-case) about the same problem but i might have been to long winded so thats why i posted again. I think i use auto layout properly, but inside this class i don't use auto layout because its much shorter and cleaner this way than to use constraints in this case, i think. – quad16 Jun 02 '16 at 06:31
  • I'd recommend looking at something like [OAStackView](https://github.com/oarrabi/OAStackView) if you want that functionality but need to support older versions of iOS. I use it extensively in my current project and it works wonderfully. – GCBenson Jun 02 '16 at 10:08

0 Answers0