UIScrollView with dynamically sized content

后端 未结 2 1865
温柔的废话
温柔的废话 2020-12-06 23:47

(Xcode 11, Swift)

Being a newbie to iOS and Autolayout, I\'m struggling with implementing a fairly simple (IMHO) view which displays a [vertical] list of items. The

2条回答
  •  臣服心动
    2020-12-07 00:30

    Alignment constraints (leading/trailing/top/bottom)

    The alignment constraint between Scroll View and Content View defines the scrollable range of the content. For example,

    • If scrollView.bottom = contentView.bottom, it means Scroll View is scrollable to the bottom of Content View.
    • If scrollView.bottom = contentView.bottom + 100, the scrollable bottom end of Scroll View will exceed the end of Content View by 100 points.
    • If scrollView.bottom = contentView.bottom — 100, the bottom of Content View will not be reached even the scrollView is scrolled to the bottom end.

    That is, the (bottom) anchor on Scroll View indicates the (bottom) edge of the outer frame, i.e., the visible part of Content View; the (bottom) anchor on Content View refers to the edge of the actual content, which will be hidden if not scrolled to. Unlike normal use cases, alignment constraints between Scroll View and Content View have nothing to do with the actual size of Content View. They affect only “scrollable range of content view” but NOT “actual content size”. The actual size of Content View must be additionally defined.

    Size constraints (width/height)

    To actually size Content View, we may set the size of Content View to a specific length, like width/height of 500. If the width/height exceeds the width/height of Scroll View, there will be a scrollbar for users to scroll. However, a more common case will be, we want Content View to have the same width (or height) as Scroll View. In this case, we will have

    contentView.width = scrollView.width

    The width of Content View refers to the actual full width of content. On the other hand, the width of Scroll View refers to the outer container frame width of Scroll View. Of course, it doesn’t have to be the same width, but can be other forms like a * scrollView.width + b. And if we have Content View higher (or wider) than Scroll View, a scrollbar appears. Content View can not only be a single view, but also multiple views, as long as they are appropriately constrained using alignment and size constraints to Scroll View.

    For details, you may follow this article: Link.

提交回复
热议问题