2016-08-01 4 views
0

Когда я использовал initWithFrame, все было в порядке. Но мои руководители сообщили, что autoLayout - это, как правило, более эффективная практика. Поэтому я попытался добавить 4 привязки к imageView, и внезапно он не появится на моих экранах, когда я запустил его на симуляторе.iOS autoLayout просмотр не отображается на экране?

- (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; 
} 

А потом в методе loadView у меня есть ...

[self.view addSubview:self.titleImage]; 

Когда я использовал initWithFrame x, y, width, height он работал отлично. Я удалил эту строку и добавил 4 ограничения, и теперь я не могу заставить ее отображаться на моем экране.

+0

Вы должны добавить ограничения ПОСЛЕ addSubview –

+0

поэтому я не могу добавить ограничения в моем инкубаторе? – BeefJurky

ответ

2
  1. Вы должны добавить _titleImage в качестве подзаголовка перед добавлением ограничений.
  2. В любом режиме вы используете с AutoLayout, вы должны вызвать:

    [_titleImage setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    
+0

, который сделал это, спасибо – BeefJurky