Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto Layout causes infinite layoutSubviews loop

I'm really puzzled by this, when I use auto layout on a subview the layoutSubview method loops infinitely.

All I'm doing is:

- (id)init
{
    self = [super init];
    if(self)
    {
        self.backgroundColor = [UIColor grayColor];
        _imageView = [[UIImageView alloc] init];
        _imageView.translatesAutoresizingMaskIntoConstraints = NO;
        [self addSubview:_imageView];

        [self applyConstraints];

    }
    return self;
}

-(void)applyConstraints
{
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_imageView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView)]];
    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_imageView]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_imageView)]];
}

And this causes an infinite loop in layoutSubviews. Actually even when applyConstraints is not called the loop occurs, the only way to stop it from happening is setting 'translatesAutoresizingMaskIntoConstraints' to YES.

Has anyone encountered/solved this problem before?

Update Just to clarify, this is an UIView subclass, which is used within a view controller. The view itself does not use auto layout, instead it's frame is set the old fashioned way after initialization.

like image 298
Alvin Avatar asked Nov 28 '22 02:11

Alvin


2 Answers

This might help you.

layoutSubviews will be called

  • When frame of the view changes
  • When a view removed from the superview then it will be called on superview
  • In UIScrollview, during scrolling.
  • While adding the view to superView.
  • During orientation change.
like image 116
Prasad Devadiga Avatar answered Dec 05 '22 05:12

Prasad Devadiga


The loop was caused by one of the superviews, which was removing its subviews, setting their (possibly new) frame and then re-adding them. As the piece of code was absolutely unnecessary I removed it which fixed the problem.

like image 31
Alvin Avatar answered Dec 05 '22 05:12

Alvin