2016-08-01 59 views
0

当我使用initWithFrame时,一切都很好。但我的主管建议autoLayout通常是一种更好的做法。所以我试图给imageView添加4个约束,当我在模拟器上运行它时,它突然不会显示在我的屏幕上。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 xywidthheight它是工作的罚款。我删除了该行并添加了4个约束条件,现在我无法将它显示在屏幕上。

+0

你需要在你addSubview –

+0

所以我不能在我的二传手添加约束添加约束? – BeefJurky

回答

2
  1. 在添加约束之前,您应该添加_titleImage作为子视图。
  2. 在你使用自动版式使用任何视图,你必须调用:

    [_titleImage setTranslatesAutoresizingMaskIntoConstraints:NO]; 
    
+0

做到了,谢谢 – BeefJurky