Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSLayoutConstraints and setting the width/height of a view dynamically

I have a question about setting the size of a view to which i'm applying some layout constraints.
How can I define the size of the view without defining its frame?

I'm trying to create a view that has its height fixed and has an origin at the screen origin. It fills the width of the view, so that when the device rotates the view extends to the width of the screen. This is what I've got so far...

self.containerView = [[HitTestContainerView alloc] init]; [self.containerView setBackgroundColor:[UIColor redColor]]; [self.view addSubview:self.containerView];  NSDictionary *viewsDictionary = @{@"view":self.containerView}; NSArray *verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-50-[view]-250-|" options:0 metrics:nil views:viewsDictionary]; NSArray *horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil views:viewsDictionary]; [self.view addConstraints:verticalConstraints]; [self.view addConstraints:horizontalConstraints]; 

The problem is I can't get anything to show up on the screen unless I set the frame of that containerView. What is the correct way to do this without using Interface Builder?

like image 437
Sean Danzeiser Avatar asked Oct 12 '12 18:10

Sean Danzeiser


1 Answers

I wrote a little tool that will assist you with this:

http://autolayoutconstraints.com

Here is the answer to your question autogenerated by the tool

Objective-C

// align view from the left and right [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[view]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];  // width constraint [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[view(==250)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]];  // height constraint [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[view(==50)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(view)]]; 

Swift

// align view from the left and right self.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[view]-10-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));  // width constraint self.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[view(==250)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view]));  // height constraint self.containerView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[view(==50)]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": view])); 
like image 67
Chad Scira Avatar answered Sep 29 '22 01:09

Chad Scira