BeefJurky
BeefJurky

Reputation: 63

iOS autoLayout views not showing on screen?

When I was using initWithFrame, everything was fine. But my supervisors advised that autoLayout is generally a better practice. So I tried adding 4 constraints to an imageView, and suddenly it won't show up on my screens when I run it on the simulator.

- (UIImageView *) titleImage
{
    if (!_titleImage){
        _titleImage =[[UIImageView alloc] init];
        _titleImage.image = [UIImage imageNamed:@"Example.png"];

        [self.view addConstraint:
         [NSLayoutConstraint constraintWithItem:_titleImage
                attribute:NSLayoutAttributeTop
                relatedBy:NSLayoutRelationEqual
                toItem:self.view
                attribute:NSLayoutAttributeTop
                multiplier:1.0
                constant:100]];
        [self.view addConstraint:
         [NSLayoutConstraint constraintWithItem:_titleImage
                attribute:NSLayoutAttributeLeading
                relatedBy:NSLayoutRelationEqual
                toItem:self.view
                attribute:NSLayoutAttributeLeading
                multiplier:1.0
                constant:100]];
        [self.view addConstraint:
         [NSLayoutConstraint constraintWithItem:_titleImage
                attribute:NSLayoutAttributeTrailing
                relatedBy:NSLayoutRelationEqual
                toItem:self.view
                attribute:NSLayoutAttributeTrailing
                multiplier:1.0
                constant:-100]];
        [self.view addConstraint:
         [NSLayoutConstraint constraintWithItem:_titleImage
                attribute:NSLayoutAttributeBottom
                relatedBy:NSLayoutRelationEqual
                toItem:self.view
                attribute:NSLayoutAttributeBottom
                multiplier:1.0
                constant:-100]];
    }
    return _titleImage;
}

And then in the loadView method I have...

[self.view addSubview:self.titleImage];

When I just used initWithFrame x, y, width, height it was working fine. I removed that line and added 4 constraints and now I can't get it to show up on my screen.

Upvotes: 0

Views: 103

Answers (1)

MCMatan
MCMatan

Reputation: 8843

  1. You should add _titleImage as a subview before you add constraints.
  2. On any view you're using with AutoLayout, you must call :

    [_titleImage setTranslatesAutoresizingMaskIntoConstraints:NO];
    

Upvotes: 2

Related Questions