How can I get an NSView to resize to fit the desired sizes of its subviews using Auto Layout?

扶醉桌前 提交于 2019-12-03 07:49:54

问题


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.

来源:https://stackoverflow.com/questions/9034527/how-can-i-get-an-nsview-to-resize-to-fit-the-desired-sizes-of-its-subviews-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!