Search code examples
iosswiftuiviewcontrolleruiscrollview

How to add UIViewController into UIScrollView in swift?


I want to add UIViewController into UIScrollView.
I searching and tried, but I can't find solution.
The most understandable way is this.

Here is my code.

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var scrollView: UIScrollView!



    override func viewDidLoad() {
        super.viewDidLoad()

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


        let test = self.storyboard?.instantiateViewController(withIdentifier: "Test") as! TestViewController

        self.addChild(test)
        self.scrollView.addSubview(test.view)
        test.willMove(toParent: self)

        test.view.frame.origin = CGPoint.zero
    }
}

But, I this way is error like this. enter image description here enter image description here

How to add UIViewController into UIScrollView??
Please Help me.


Solution

  • In your storyboard, just drag and drop a containerView, it will make a UIViewController in your scrollView as you want