“宽等于高”的 Interface Builder 限制

我找不到一种方法来创建一个“正方形”约束,即“宽度等于高度”的 Interface Builder。我想可以通过编程方式添加这种约束。我能在 IB 做点什么吗?也许我只是没看出来?看起来微不足道,但我却找不到。

49615 次浏览

Update Xcode 5.1b5

width equals height

Ctrl+click and drag from a view and release while the pointer is over the view. Select "Aspect Ratio". It will create a constraint where the first and second item is the view.


Before Xcode 5.1

You can't because the width/height editor lacks the fields to relate to another property or set the ratio:

width constraint

Therefore, you can't express the following code in Interface Builder:

CGFloat ratio = 1.0;
NSLayoutConstraint *constraint = [NSLayoutConstraint
constraintWithItem:myView
attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:myView
attribute:NSLayoutAttributeHeight
multiplier:ratio
constant:0];
constraint.priority = 1000;
[myView.superview addConstraint:constraint];

Please add a new constraint, aspect ratio to 1:1 on the UI element as in the image.

Set Aspect ratio to 1:1

To start, control drag diagonally from the button to itself. A contextual menu will appear, where you can add width and height constraints. Shift+Click on each; a checkmark will appear indicating that you have added the constraint. (If you accidentally dismiss the dialog before adding both, that’s OK, just repeat the drag step and set the other one):

enter image description here

When first added, these constraints take on the current width and height of the button, so you’ll need to adjust each constraint to give it a more appropriate value. We’ll have to do this one at a time, although our image is square, so be sure to use the same constant value in both constraints to resize the button proportionally. Double-click on the constraint, and enter a smaller value in its constant field:

enter image description here