以编程方式添加约束时,在UIView中启用AutoLayout

时间:2014-02-13 19:15:01

标签: ios autolayout

我有一个UIView。这没什么特别的。代码如下。问题是当我运行应用程序时,从不调用updateConstraints,因此约束不会做任何事情。

我习惯通过手动计算坐标来做所有事情。包含视图就是这样做的。所以我可能会错过一些我需要转动限制的部分。它可能是什么?

@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

1 个答案:

答案 0 :(得分:2)

您可以强制系统使用自动布局,方法是将其添加到SubView

+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}

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

相关问题