UIScrollView + Centered View + Ambigous Scrollable

2019-02-01 08:47发布

问题:

I have:

  • application, that should work in landscape and portrait mode.
  • view with full-size scroll view on top.
  • some view inside scroll view with fixed width and height. (with added H and W constraints)
  • set to view inside scroll view as horizontal centered in container. (added according constraint)

I have warning in interface builder "Has ambiguous scrollable content width".

The only way to fix this problem, that I know - is set trailing and leading constraints. But for different iPhones (5.5", 4.7", 4") I need to set different trailing and leading constraints.

How can I eliminate this warning and still have centered horizontally view with fixed W and H for all iPhone sizes?

I create Github repo to illustrate this problem: ScrollViewAmbigous

This is not duplicate of UIScrollView Scrollable Content Size Ambiguity , but it similar (and not answered although), but this question especially related to different sizes of iPhones.

回答1:

In the morning with a fresh cup of coffee I figured out workaround for this issue!

So, here is the initial state for simplest case:

  1. scrollView with 0 constraints to all edges
  2. Button centered Horizontal and Vertical with fixed Width and Height
  3. And, of course Has ambiguous scrollable content width and Has ambiguous scrollable content height annoying warnings.

All, that we have to do is:

  • Add 2 additional constraints, for example "0" for trailing and/or bottom space for our view (in my case - UIButton)

Important: you have to add trailing and/or bottom constraints. Not "leading and top" - it's not works!

You can check it in my example project, that demonstrating how to fix this issue: ScrollViewAmbigous

P.S.

I don't know why it works and how Xcode detect which constraint is more prioritised (because I'm not set priority for these constraints explicity), but I'll be thankful if someone explain, why it works in comments below.



回答2:

Problem :

  1. The warning is telling us that the the content size of the scrollview depends on its subviews.
  2. while your subview don't have any strict rule of position and size (no fixed constraints) it will confuse nib generated scrollview content size.

Solution :

  1. Make only one subview as a 'contentView' for scrollview.
  2. Add strict (fixed) constraints to that 'contentView'.

    Best practice : equal width and height to its scroll view.

  3. Add all other subviews and constraints to your 'contentView'.


回答3:

There seems to be a lot of confusion on this issue. My take is that a UIScrollView must have TWO trailing space constraints, an 'inner' one connecting it to one of it's subviews (so it can know its content width), and another 'outer' one connecting it to a sibling or superview so it knows its frame width.

Same principle applies for height, i.e. two bottom space constraints.