Trouble with UIScrollView and Constraints

2019-08-14 18:55发布

I'm having trouble with UIScrollView and Constraints.

I want to display a FAQ inside my application. This will include several questions and answers, with various length. It won't change after launch, so I handle everything directly in the storyboard. However, it has to work on different iPhone screen size (from iPhone 5 to iPhone 6 Plus).

So what I'm trying to do is :

UIView
  UIScrollView
     UIView (FAQ1)
        UILabel (Question 1)
        UITextView (Answer 1)
     UIView (FAQ2)
        UILabel (Question 2)
        UITextView (Answer 2)
     ...

Here is an example of what it looks like (color on purpose, to see at runtime) : Storyboard

Now if I apply some constraints, I manage to get that : iPhone 6 Plus

However it is not scrollable and the text is out on the right side.

If I run the same thing on a smaller screen, I get that : iPhone 5

Which is scrollable this time (not more than what you see on the screenshot...) and the text is still out.

Is there anyone who could help me understanding how to use Constraints properly with an UIScrollView ?

If possible the text size has to shrink on small screens. If it isn't, it should keep the same size but the UITextView will be scrollable too.

1条回答
祖国的老花朵
2楼-- · 2019-08-14 19:33

The best way to use scrollview and auto layout is to add a view inside the scrollview and pin all its edges to scroll view and equal widths to superview, Pin all edges of scrollview to superView

  1. pin top, left , right and height of your label to your FAQ1 view.
  2. pin top of your text view to label and left right and bottom to your FAQ1 view.
  3. pin the height of your FAQ1 view, and left and right of your faq1 view to content view.
  4. Follow step 1 to 3 for all your faq views.
  5. Pin top of your faq1 view to top to top of content view
  6. Pin the top of the next faq view to bottom of the previous faq view.
  7. pin bottom of the last faq view to bottom of content view

when adding your faq1 view pin its top to top ,left and right to contentView's top left and right with necessary padding.

You can find the sample code here Hope this solves your problem

查看更多
登录 后发表回答