2014-02-13 77 views
0

我有一个UIView。这不是什么幻想。代码如下。问题是,当我运行应用程序时,updateConstraints从不被调用,所以约束不会执行任何操作。以编程方式添加约束时在UIView中启用AutoLayout

我习惯于通过手动计算坐标来做所有事情。包含的视图完全如此。所以我可能会缺少一些我需要打开约束的部分。会是什么呢?

@implementation Subview 

-(void) createFooButton { 
    UIButton* foo = [[UIButton alloc]init]; 
    self.fooButton = foo; 
    [foo setTitle:@"foo" forState:UIControlStateNormal]; 
    [foo sizeToFit]; 
    [self addSubview:foo]; 
    UIColor* green = [UIColor greenColor]; 
    foo.translatesAutoresizingMaskIntoConstraints = NO; 
    [foo setBackgroundColor:green]; 
} 

-(void) createBarButton { 
    UIButton* bar = [[UIButton alloc]init]; 
    [bar sizeToFit]; 
    self.barButton = bar; 
    [bar setTitle:@"bar" forState:UIControlStateNormal]; 
    bar.translatesAutoresizingMaskIntoConstraints = NO; 
    [self addSubview:bar]; 
    UIColor* red = [UIColor redColor]; 
    [bar setBackgroundColor:red]; 

} 

-(void) addLayoutConstraints { 
    UIButton* foo = self.fooButton; 
    UIButton* bar = self.barButton; 
    NSLayoutConstraint* constraint = [NSLayoutConstraint constraintWithItem:foo attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:100]; 
    NSLayoutConstraint* constraint2 = [NSLayoutConstraint constraintWithItem:bar attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:foo attribute:NSLayoutAttributeBottom multiplier:1 constant:20]; 
    NSArray* array = @[constraint, constraint2]; 
    [self addConstraints: array]; 
} 

-(void) updateConstraints { 
    [self addLayoutConstraints]; 
    [super updateConstraints]; 
} 

- (id)initWithFrame:(CGRect)frame { 
    if ((self = [super initWithFrame:frame])) { 
     self.backgroundColor = [UIColor cyanColor]; 
     [self createFooButton]; 
     [self createBarButton]; 
     self.autoresizesSubviews = false; 
     self.translatesAutoresizingMaskIntoConstraints = NO; 
    } 
    return self; 
} 

@end 

回答

2

您可以强制系统中加入这SubView使用自动布局:

+ (BOOL)requiresConstraintBasedLayout { 
    return YES; 
} 

注意,这是一个类的方法,而不是一个实例方法。

相关问题