How can I get an NSView to resize to fit the desir

2019-03-11 15:27发布

I have a superview with three subviews. Two of those subviews are fixed in size and position within the superview, but the third can vary in size depending on its contents.

I have set up auto layout constraints to set the size and position of each of the sub views, but what I would like to happen is that when the contents of the third view change, the superview should resize to be able to display it fully.

I have implemented - (NSSize) intrinsicContentSize on that subview so that it returns the size it would like to be, but I can't work out how to add a constraint which will trigger the superview to resize.

Any ideas?

UPDATE:

I've got this working by adding constraints to the view like this:

sizeWidthConstraint = [[NSLayoutConstraint constraintsWithVisualFormat:@"H:[self(==viewWidth)]" options:0 metrics:metrics views:views] lastObject];
sizeHeightConstraint = [[NSLayoutConstraint constraintsWithVisualFormat:@"V:[self(==viewHeight)]" options:0 metrics:metrics views:views] lastObject];

where "viewWidth" and "viewHeight" are keys in the metrics dictionary with the desired values. In udpateConstraints I can then analyse the contents of my view and do this:

[sizeHeightConstraint setConstant: size.height];
[sizeWidthConstraint setConstant: size.width];

to set new values and the next layout will cause the view to be resized.

UPDATE in answer to panupan's question:

When you create a constraint in this way, you can put in what is essentially a variable name. In this case, those names are viewWidth and viewHeight. They're known as the constants of the constraint. You also pass in a dictionary, called the metrics, to the [NSLayoutConstrating constraintsWithVisualFormat:...] call that give values for those constants.

So, in this case, I start out with the default height and width for my view as the values for the metrics dictionary keys viewWidth and viewHeight. Later on, I use the setConstant: method to change those values. In the example above, size is a CGSize structure that I have calculated from the contents of the view (i.e. based on the sizes of its subviews) and I am using the width and height values to adjust the constants.

This doesn't achieve quite what I was after, in that it doesn't cause the size of my view to re-size automatically based on the intrinsic sizes of the subviews, but it does give me a way to re-size it manually.

0条回答
登录 后发表回答