2014-02-13 117 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; 
} 

注意,這是一個類的方法,而不是一個實例方法。

相關問題