1

I'm creating a application using Swift3, and i have difficult to define correctly height for UIScrollView, i'm using autolayout and create this structure:

  • UIScrollView
    • UIView // The container view
    • UIImageView // Constraint Top Edges = 20 in relation to UIView
    • UITextView // Constraint Top Edges = 40 in relation to UIImageView
    • UITextView // Constraint Top Edges = 20 in relation to UITextView
    • UIButton // Constraint Top Edges 30 in relation to UITextView

Currently, i'm using this logic to calculate UIScrollView height

override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize.height = scrollHeight

}

But, i can only get the views height, and them not consider the Constraints "margins", i would like know any way to calculate correct height for UIScrollView, adjusted according their content.

  • If you add a constraint to the last button to the bottom of the scrollview you should it have to set the size of the content manually. – agibson007 Jul 07 '17 at 11:26
  • @agibson007 but i don't add this constraint, only add constraint to the bottom of the uiview above – mauricio caserta Jul 07 '17 at 11:30
  • 1
    Yep that’s what I meant sorry. That should work. See this answer I gave a while ago. https://stackoverflow.com/questions/42684594/ios-uiscrollview-with-dynamic-content-using-containerview-step-by-step/42685952#42685952 – agibson007 Jul 07 '17 at 11:32

2 Answers2

0

Close! Let's add the top margin for each view:

override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height

        //Add the margins as well to the scrollHeight
        scrollHeight += view.layoutMargins.top
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize = CGRect(x: self.scrollView.contentSize.width, y: scrollHeight)
}
impression7vx
  • 1,728
  • 1
  • 20
  • 50
0

self.scrollview.contentsize.height = containerview.height;