Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Auto Layout - nested width and dynamic height

Tags:

ios

autolayout

Simple goal, but it demonstrates situations where Auto Layout gives me a headache. I want to have a stack view with a width of 256pt and a dynamic height based on layout (I shouldn't have to manually specify the height). Inside it should be an image view sized 64pt x 64pt, which should also be centered horizontally as well as constrained 8pt from the superview's top. Note that the image view isn't the only child, hence why the stack view's height must be sized dynamically.

Auto Layout now tells me there's a conflict between the 256pt width constraint of the stack view and the 64pt width constraint of the image, as well as some mysterious "leading = Image.leading" and "trailing = Image.trailing" conflict which I can't even delete nor find.

Am I missing out something here regarding Auto Layout? I expect all logic to be contained in the interface builder, so no code should be required.

Running Xcode 9.1

Layout image

like image 271
Johan Svensson Avatar asked Sep 20 '26 17:09

Johan Svensson


1 Answers

There is nothing to confuse. iOS clearly telling you the issue.

StackViews take size based on the size of child components (this is called implicit size) unless its been overriden manually as in your case which is 256pt.

Because stackView is just a container for multiple childViews stacked either horizontally or vertically, now because you have added only one imageView to it, it adds the leading and trailing constraint to it which makes absolute sense because you added a single view to the stack of view's , now what should stackView do? stretch childView (in your case imageView) to its own size.

But then you did not allow it because you added width constraint to imageView now when it tries to increase the imageView's width imageView's constraint wont allow it.

Hence it is complaining that there are too many conflicting constraints. Thats all :)

some mysterious "leading = Image.leading" and "trailing = Image.trailing" conflict which I can't even delete nor find.

You cant delete them because, imageView is the only view inside stackView. Because there is only one child view to stack, stackView will start from left side (leading) to right side (trailing). Because now stackView has its own width it tries to change the width of imageView to reflect the same! But images width constraint prevents it from happening.

What are you trying to achieve with imageView added to stackView. If there is only one view in stackView, adding stackView does not make any sense. Reconsider what you are doing.

Finally, when you have only one childView in stack view, adding horizontal center does not make any sense (no matter vertical/horizontal stackView).

like image 169
Sandeep Bhandari Avatar answered Sep 23 '26 09:09

Sandeep Bhandari