Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Set UIScrollView 'main' content to be height of screen - with 'secondary' content 'below the fold'

I've been banging my head against the wall with this one for a while now.

I have a single view application that has it's main content displayed in a scroll view - initially so that pull to refresh could be implemented easily. This is working and implemented using storyboards and AutoLayout constraints.

I have got a new feature that I would like to implement, however I don't want it to always be visible, I want it to be displayed underneath the 'main' content in the scroll view. This way, the user must scroll the main view in order to see the extra content. I've made up a small diagram that will hopefully convey this better than words:

UIScrollView Diagram

I have tried simply placing the secondary content underneath the last block of main content with a vertical constraint - this lets you scroll to it, but the Scroll View snaps back to it's original position once you let go.

Any tips on how to solve this are very welcome, thank you!

Edit:

Here is a simplified hierarchy of what I have tried:

  • UIScrollView
    • Scrolling Content
      • Main Content View
        • Content...
      • Secondary Content View
        • Content...

I think the difficulty is arising because I want the Main Content View to be the full height of the screen.

like image 359
TreeTrum Avatar asked Oct 20 '25 04:10

TreeTrum


1 Answers

You might have to position your views inside your scrollview, and set the contentSize of the scrollView.

View Controller

@IBOutlet weak var scrollView: UIScrollView!

let height = UIScreen.main.bounds.height
let width = UIScreen.main.bounds.width

override func viewDidLoad() {
    super.viewDidLoad()
    /* Set the contentSize of the scrollview */
    self.scrollView.contentSize = CGSize(width: width, height: height*2)

    /* Adding two views, red, green at different locations inside the scrollview */
    let red = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
    red.backgroundColor = UIColor.red

    let green = UIView(frame: CGRect(x: 0, y: height, width: width, height: height))
    green.backgroundColor = UIColor.green

    /* Adding the views in the scrollview */
    self.scrollView.addSubview(red)
    self.scrollView.addSubview(green)

}

Demo

Example

like image 192
Miket25 Avatar answered Oct 21 '25 18:10

Miket25



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!