iosswiftuiscrollviewfreeform

Initially unscrollable scrollView?


Because I have a scroll view, I have set my View Controller to freeform with a fixed size (since that was what I learnt). I want to have my scroll view such that it starts with the same contentSize and scrollable size (so that initially you can't scroll), then later after buttons are pressed the scrollable height increases so that you can scroll. I had tested all this on the iPhone Xr model simulator, and it was all working well until I tried switching to a different iPhone model (iPhone 7+). When I tested my program with the 7+ (which is shorter in height), the scrollView was initially scrollable (which it wasn't supposed to), and I think it might be because I have set my View Controller to freeform with a fixed size (which fits the iPhone Xr model which is taller), so when I try using a smaller iPhone model, it still has the same bigger length so it initially is scrollable.

What I want to get is have my scrollView go from the top of the screen of the iPhone to about halfway, x above a button I have. What I had initially was:

scrollView.contentSize.height = 404

Which I now know is completely wrong since I was hard coding it, but I don't know how else I can find the height from the top of the iPhone screen to the button. Perhaps its something along the lines of:

scrollView.contentSize.height = button.frame.origin.y - /*y position of top of iPhone screen*/

I also considered that the height of the scrollView might just be the y position of the button, however, because I have a fixed View Controller height, for iPhones with smaller displays, that would make the scrollView much larger than what I want (a size such that you initially can't scroll).

Hopefully this makes sense, thanks.

Image that may help explain


Solution

  • How to get the screen size:

    let screenFrame = UIScreen.main.bounds   // returns a CGRect
    
    let screenHeight = screenFrame.height    // returns a CGFloat
    

    Edit: If you are trying to go completely using storyboard, try setting required constraints from the scrollView to the view to get it where you want.

    The height of the contentView inside the scrollView can then be set equal to the height of the scrollView, but with a low priority.

    I think that should work, though it's easier to explain when starting from scratch. Let me know how it goes.