简体   繁体   中英

NSView Contraints - How can I force the aspect ratio of a subview to stay constant?

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!

This can be done by setting up most of the constraints in IB, then changing one of them in code. The static subview should have whatever spacing constraints you want to the sides and bottom of the resizable view, and a fixed height constraint -- after making those, you should be able to delete the constraint to the top of the resizable view if there is one. Make an IBOutlet to the height constraint, and change that in code like this (heightCon is my outlet, and this code is in the static subview subclass):

- (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];
}

The .54 number came from my initial ratio of height to width in IB.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM