user2512523
user2512523

Reputation: 1359

Adding view controller in scrollview

I am currently working on an app that has been developed using storyboards.

I am trying to add a view controller programmatically into a paging scroll view at the beginning before 2 other views that are already added within the storyboard.

The view controller gets added but the width is slightly larger and goes across into the middle view.

let vc = Vc()
scrollView.addSubview(vc.view)

Upvotes: 0

Views: 5427

Answers (1)

anho
anho

Reputation: 1735

You have to assign a contentSize to the scrollview and a position for the frame of the ViewController

scrollView.contentSize = CGSize(width: 2 * view.frame.width, height: scrollView.frame.height)
    
let frameVC = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
        
vc.view.frame = frameVC

vc.willMoveToParentViewController(self)
self.addChildViewController(vc)
vc.didMoveToParentViewController(self)
scrollView.addSubview(vc.view)

Note that you have to change the frameVC to match your requirements

Swift 5 sytax update

scrollView.contentSize = CGSize(width: 2 * view.frame.width, height: scrollView.frame.height)
    
let frameVC = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
        
vc.view.frame = frameVC

vc.willMove(toParent: self)
addChild(vc)
vc.didMove(toParent: self)
scrollView.addSubview(vc.view)

Note: Frames vs Constraint layout

Instead of using a frame you can also use create a constraint layout to add a UIView to a UIScrollView

scrollView.contentSize = CGSize(width: 2 * view.frame.width, height: scrollView.frame.height)
    
scrollView.addSubview(vc.view)

vc.view.translatesAutoresizingMaskIntoConstraints = false

// add constrains here

vc.willMove(toParent: self)
addChild(vc)
vc.didMove(toParent: self)

Upvotes: 8

Related Questions