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?
I wrote a little tool that will assist you with this:
http://autolayoutconstraints.com
// 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)]];
// 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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With