0

Having trouble implementing the following:

+-------------------+
|                   |
|                   |
|     RESIZABLE     |
|                   |
|      NSVIEW       |
|                   |
|                   |
|                   |
|                   |
|                   |
|                   |
|                   |
|                   |
|                   |
|+-----------------+|
||                 ||
||     STATIC      ||
||                 ||
||     SUBVIEW     ||
||                 ||
|+-----------------+|
+-------------------+

Where the aspect ratio of the subview must stay constant (as the user changes the width of the resizeable view).

I'd like to do it using constraints, so far I've got:

//This is a snippet of the resizable view class

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:subview attribute:NSLayoutAttributeWidth multiplier:1 constant:0]];
[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:subview attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];

//This is a snippet of the subview class

[self addConstraint:[NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:aspectRatio constant:0]];

The frame of the resizable view is initially set. In this case it would make sense not to set the frame of the subview? At the moment, the main view just seems to disappear - it starts width a width of zero.

How should I go about this - I'd love to use constraints if possible!

4

1 回答 1

3

这可以通过在 IB 中设置大多数约束,然后在代码中更改其中一个来完成。静态子视图应该对可调整大小的视图的侧面和底部有任何间距约束,以及一个固定的高度约束——在完成这些之后,如果有一个,你应该能够删除到可调整大小视图顶部的约束. 为高度约束创建一个 IBOutlet,并在这样的代码中进行更改(heightCon 是我的出口,此代码位于静态子视图子类中):

- (void)awakeFromNib {
    [self removeConstraint:self.heightCon];
    self.heightCon = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeWidth multiplier:.54 constant:0];
    [self addConstraint:self.heightCon];
}

.54 数字来自我在 IB 中的初始高宽比。

于 2013-05-13T15:57:37.867 回答