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?
To define the height and width of a view using layout constraints, you, uh, define the height and width of the view using layout constraints. For example, you are already saying:
So you could just change that to:
Now the view will be 50 pixels from the top of its superview, and 40 pixels tall.
Alternatively you can use
constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:to set the height constraint; thetoItemwill be nil, of course, since there is no relationship to another view.