0

I have a UIView. It is nothing fancy. The code is below. The problem is that when I run the app, updateConstraints is never called, so the constraints don't do anything.

I am used to doing everything by computing the coordinates manually. The containing view does exactly that. So I may be missing some piece I need to turn the constraints on. What could it be?

@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 Answer 1

2

You can force the system to use auto layout by adding this to SubView:

+ (BOOL)requiresConstraintBasedLayout {
    return YES;
}

Notice that this is a class method, not an instance method.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.