13
votes

I tried to create a custom freefrom view with interface builder. I have a UIView which is containing a UIImageView and UILabel. I set the constraints to adjusting the Label according to the Image etc and a margin to the superview.

Now I want the superview to exactly fit the subviews. But when I press Editor -> Size To Fit Content, the superview is not resized completely and the constrains are in conflict. What there appears is a implicit constraint ("iPhone Portrait Screen Height"), which can not be altered/deleted. See Screenshot below:

enter image description here

3
I have also run into this problem today. It seems to me that the root view is always being treated as if it's going to be the size of the whole screen even though I set it as freeform. I'm considering filing a bug with Apple. - Nikola Lajic
Did you find a solution to this? I am having the same issue today. - Kremk
Any update on this? Still seems to be an issue. - Tylerc230
Had a similar problem with "iPhone Portrait Screen Width" with equal width views and explicit trailing constraints ("gaps") between. Just needed to remove an explicit width I set on the first view which caused it to be over-constrained. - David James

3 Answers

1
votes

While not ideal, depending on how your XIB is structured and how you are referencing the view, you could create a "scratch pad" view and place your custom view inside of that just to see how everything will layout. That is if you're setting the view to an outlet defined in the XIB's File Owner, you can just connect it to the view you've created inside the "scratch pad".

For example, I created a container view with a square and a switch inside. The top example complains of conflicting constraints and doesn't layout correctly, while the bottom example shows the same thing centered in a throw-away view. Again, not ideal, but it's working for me.

enter image description here

Edit: I just realized that some size class constraints may be lost once the "scratch pad" view is discarded so that is another wrinkle to consider. Still looking into this.

0
votes

Just to make it simple forget the label for the time being. You have already added the width and height constraint of the image view, now instead of using sizetofit content, try adding leading, trailing, top and bottom constraints between the image view and it's parent view. With that your parent view should fit the image view.

The same technique (constraints to parent view) can be used to get it work with the image view and label together.

0
votes

I noticed that when I physically dragged the superview's width and height to satisfy the constraints, the red constraint errors went away along with the "iPhone Portrait Screen Width" constraint. In other words, my constraints dictated that my subview be bottom aligned with its super view. If I dragged the superview's bottom edge up to align flush with the subview, the errors went away. Still seems buggy and unintuitive.