0

I have a UIViewController that acts as a Container View Controller. It has a UIScrollView that has the same width as the screen, but it's height is smaller than the height of the screen.

The UIScrollView contains the views of two other UIViewControllers and those views can be horizontally scrolled through.

I set my contentSize like this:

scrollView.contentSize.width = self.view.bounds.width * 2

This works and allows me to scroll through my UIViewController views horizontally.

The following is how I add the UIViewController views to my scrollView:

private func addPanel(viewController: UIViewController, panel: Panel) {

    let xOffset: CGFloat!
    switch panel {
    case .left:
        xOffset = 0.0
    case .right:
        xOffset = self.view.bounds.width
    }

    let panelView = UIView(frame: CGRect(x: xOffset, y: 0, width: self.view.bounds.width, height: self.scrollView.bounds.height))

    scrollView.addSubview(panelView)

    let panelViewController: UIViewController! = viewController

    var viewBounds = view.bounds
    viewBounds.height = panelView.bounds.height

    panelViewController.view.frame = view.bounds
    panelView.addSubview(panelViewController.view)
    addChildViewController(panelViewController)
    panelViewController.didMove(toParentViewController: self)
}

For some reason, the UIViewController views don't resize to fit the height of the UIScrollView.

Should I be doing it constraint based? How would I do this. I've been struggling with this for a few days and am at a loss.

Essentially, the UIViewController views will just like like full screen views offset and so you can't see the bottom of the views because the bottom of the screen cuts them off.

David
  • 7,028
  • 10
  • 48
  • 95
  • It would be easier to help if you posted the actual code you are using - or at least a stripped-down version that runs and demonstrates the issue. Looking at the code you posted, it looks like you are setting the height of `panelViewController.view` to the height of `view` when you probably want to set it to the height of `scrollView` ... or `panelView`, which becomes the superview of `panelViewController.view`. (It can also help to use not-so-confusing names, and to add comments.) – DonMag May 14 '17 at 22:52

1 Answers1

0

I'm just taking a guess without knowing all the code, but one reason could be if you're adding the child view controllers before the scrollview has been layouted.

After you add and set the child views sizes, the scrollview adjusts its size to the phone size but you never update the child views.

My suggestion here would be to add the child view controllers to the scrollview, but move the frame setting code into a layouting method where you know your views have the correct(visible) frames/bounds.

Given you are writing this in a view controller, one method could be -viewDidLayoutSubviews

Hope this makes sense, feel free to ask more questions if it doesn't.

Andrei Stanescu
  • 6,353
  • 4
  • 35
  • 64