Search code examples
iosswiftuiscrollviewuitextview

Fit UIScrollView to the content


I've too much space below content in scroll view.

Please refer to the screenshot below. How do I fit scroll view to the content. The problem seems to be the bottom space. If I just leave it as per auto layout it gets too much space below the content.

If I set it to 8 it works but storyboard complains for constraints, see screenshot no. 2 below. If this can be fixed then I'll have solution.

I've seen some suggestions (e.g. How do I auto size a UIScrollView to fit the content) on other posts but they don't solve the issue. How to fix it?

enter image description here

enter image description here


Solution

  • Needed constraints:

    • ScrollView : top , leading , trailing , bottom

    • contentView : top , leading , trailing , bottom => to superView && equal width to main outer view

    • textView : top , leading , trailing , bottom => to contentView , height ( such as 50 )

    BTW you don't need all of this as the UITextView inherits from UIScrollview, so it's scrollable by default.
    If you need to resize it according to written text, then use:

    self.textView.frame.size = self.textView.contentSize