AutoLayout to keep view sizes proportional

前端 未结 9 852
南笙
南笙 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:15

    Just select the aspect ratio :

    enter image description here

    0 讨论(0)
  • 2020-12-05 00:19

    I'm probably late in coming up with a solution but this can actually be made very easily in IB.

    First, add a UIView and pin in to all four edges of the superview.

    Then, Add your first subview and position it accordingly (ig : x = 0, y = 0, height = fixed height, width = The width you would like relative to the UIView we pinned to all four edges).

    Select both the UIView and the first subview and add an Equal Widths constraint. Of course, this will show you an error in positioning in the autolayout, but that's OK because this is not (yet) what you want.

    Now comes the trick : select the Equal Widths constraint and edit the Multiplier to be the ratio you want (eg : 1:4 if you want the first subview to be 1/4 of the UIView). Repeat steps for the second subview and Tadaaaaaa !

    enter image description here

    0 讨论(0)
  • 2020-12-05 00:19
    1. Remove the two width constraints in code, or lessen their priorities in IB, otherwise you are over-constrained.
    2. Add a constraint to describe the width ratio between the green view and blue view, in code:

      // Assuming the ratio you want is green_view_width : blue_view_width = 1 : 2
      NSLayoutConstraint *c = [NSLayoutConstraint constraintWithItem:greenView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:blueView attribute:NSLayoutAttributeWidth multiplier:0.5f constant:0.f];
      [commonSuperview addConstraint:c];
      
    0 讨论(0)
提交回复
热议问题