Question

I have a window in interface builder and a view. I have resized the window to be the size I want it. I want the window to stay the same width but resize to hug content vertically. I have set a minimum size on the window. The window is not user resizeable. I add the view to the window in the app delegate and add horizontal and vertical center position constraints.

I cannot prevent the window from hugging the content horizontally. Even with the minimum size on the window, even setting horizontal content hugging priority on contentView to 1, setting the frame on the window, nothing seems to work. What am I missing?

Was it helpful?

Solution

It’s not super-clear what you’re doing here or how it’s failing, but I’ll take a shot.

You seem to want to add a view to a window, and have the window resize vertically to fit the content, but not resize horizontally ever. Ok.

First off, the window’s minimum size doesn’t come into play here. It’s an older setting from before constraints, and if we’re using constraints you won’t use it for this issue.

Second off, the content hugging priority won’t come into play, either. The contentView isn’t going to run through its views and make sure it hugs them—if it did you’d never be able to add other, more interesting constraints, because they’d conflict.

When you add your view, you should set a horizontal center constraint (which you currently do) and then set a top and bottom alignment constraint on the new view (which you didn’t say you do), so it’s aligned with the top and bottom of its superview.

That should be all you need. You seem to indicate that the window is somehow resizing when you add a subview, which it shouldn’t do if you do these steps and ONLY these steps, so if this fails I’d have to see the code.


Edit:

You had the “view” you were adding set so it translated its autoresizing mask (which is hidden, so it’s super confusing) into more constraints, which were tripping you up. This is an artifact of the old system, and it sucks.

Here’s a photo of how I set it in the inspector (box is now unchecked). I did some other stuff to get it working, but I think if you just uncheck this box you can play with it and get it to work yourself. If not, ping me again.

XIB inspector

(On my machine I made a subview for the window’s contentView and added a width constraints to the subview, because you can’t constrain a contentView directly (which is stupid). Then I added your view to my constrained subview, and changed the y centering line two to lines constraining the tops and bottoms instead. It all worked great.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top