AutoLayout to keep view sizes proportional

前端 未结 9 876
南笙
南笙 2020-12-04 23:53

I\'m trying to achieve the following:

  • I have 2 views in my xib that need to stay 20 pixels off the edge (both sides and top)
  • The 2 views that need to
9条回答
  •  伪装坚强ぢ
    2020-12-05 00:13

    I'm new to autolayout but came across your question and thought it would be a good challenge. (That's my caveat in case this isn't the ideal solution!)

    You'll need to add the width constraints in code. I achieved this by firstly adding the two views in the NIB without width constraints. These are the constraints for the first (left) view:

    enter image description here

    These are the constraints I had for the second (right) view:

    enter image description here

    This leaves an extra constraint you don't want on the second view - leading space between superview and the second view as shown below:

    enter image description here

    You can't remove that constraint in IB as it would leave an ambiguous layout (as we don't have widths on the subviews). However you can remove it in code. Firstly, set up an outlet for it and connect it in IB:

    @property (nonatomic, strong) IBOutlet NSLayoutConstraint *view2superviewLeadingConstraint;
    

    Then, in your view controller's viewDidLoad, you can remove it using:

    [self.view removeConstraint:self.view2superviewLeadingConstraint];
    

    Finally, add the width constraints. The key here is the multiplier parameter to dicate what percentage you want the widths to be based on the superview width. Also note that you have to set the constant parameters to equal the leading/trailing totals set up in IB:

    NSLayoutConstraint *constraint1 = [NSLayoutConstraint constraintWithItem:self.view1 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.3 constant:-20];
    [self.view addConstraint:constraint1];
    
    NSLayoutConstraint *constraint2 = [NSLayoutConstraint constraintWithItem:self.view2 attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeWidth multiplier:0.7 constant:-40];
    [self.view addConstraint:constraint2];
    

提交回复
热议问题