2014-02-10 24 views
5

我有一个程序创建一个子视图,并增加了一些约束对它的看法。出于某种原因,这些约束被完全忽略。没有错误被抛出。约束根本不起作用。该子视图具有相同的框架,因为它是上海华。我期待它是400×400,并在它的父居中。我在这里做错了什么?这是我在上海华initWithFrame:方法为什么我的编程方式创建视图忽略它的约束?

- (id) initWithFrame:(CGRect)frame 
{ 
    if (self = [super initWithFrame:frame]) 
    { 
     instructionsView = [[UIView alloc] initWithFrame:frame]; 
     [self addSubview:instructionsView]; 
     [self bringSubviewToFront:instructionsView]; 

     [self addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView 
                 attribute:NSLayoutAttributeCenterX 
                 relatedBy:NSLayoutRelationEqual 
                  toItem:self 
                 attribute:NSLayoutAttributeCenterX 
                 multiplier:1. 
                  constant:0]]; 

     [self addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView 
                 attribute:NSLayoutAttributeCenterY 
                 relatedBy:NSLayoutRelationEqual 
                  toItem:self 
                 attribute:NSLayoutAttributeCenterY 
                 multiplier:1. 
                  constant:0]]; 

     [instructionsView addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView 
                    attribute:NSLayoutAttributeWidth 
                    relatedBy:NSLayoutRelationEqual 
                     toItem:nil 
                    attribute:NSLayoutAttributeNotAnAttribute 
                    multiplier:1. 
                     constant:400]]; 

     [instructionsView addConstraint:[NSLayoutConstraint constraintWithItem:instructionsView 
                    attribute:NSLayoutAttributeHeight 
                    relatedBy:NSLayoutRelationEqual 
                     toItem:nil 
                    attribute:NSLayoutAttributeNotAnAttribute 
                    multiplier:1. 
                     constant:400]]; 
    } 
    return self; 
} 

我试图改变

instructionsView = [[UIView alloc] initWithFrame:frame]; 

instructionsView = [[UIView alloc] initWithFrame:CGRectZero]; 

没有成功。

回答

9

你需要告诉视图中不使用基于自动尺寸掩膜布局,而使用自动布局

instructionsView.translatesAutoresizingMaskIntoConstraints = NO; 

documentation here

此外,视图应该没有框架来创建,这主要是一个但创建你的看法是这样的:

instructionsView = [[UIView alloc] init]; 
2

歧义可以导致令人惊讶的结果,没有引发任何异常。要歧义调试的限制,暂停在调试器和类型在LLDB命令行:

po [[UIWindow keyWindow] _autolayoutTrace] 

另外,你可以(也应该)(通过一个类别)上的UIView,允许你叫hasAmbiguousLayout递归下添加一个方法层次结构。

最后,您可以(也应该)在UIView上添加一个方法(通过类别),让您按递归调用constraintsAffectingLayoutForOrientation:

这样就可以追查究竟发生了什么事情。

相关问题