简体   繁体   中英

Add UIViewController to UIScrollView swift 3

I'm working on a ScrollView . Currently I have tow images in my ScrollView and I want to add at least a new UIViewController in the ScrollView .

That is the code which I have yet:

    self.scrollView.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.scrollView.frame.height)
    let scrollviewHeight = self.scrollView.frame.height
    let scrollviewWidth = self.scrollView.frame.width

    var imgOne = UIImageView(frame: CGRect(x: 0, y: 0, width: scrollviewWidth, height: scrollviewHeight))
    var imgTwo = UIImageView(frame: CGRect(x: scrollviewWidth, y: 0, width: scrollviewWidth, height: scrollviewHeight))

    imgOne.image = UIImage(named: "preview1")
    imgTwo.image = UIImage(named: "preview2")

    self.scrollView.addSubview(imgOne)
    self.scrollView.addSubview(imgTwo)

    self.scrollView.contentSize = CGSize(width: self.scrollView.frame.width * 2, height: self.scrollView.frame.height)
    self.scrollView.isPagingEnabled = true

Design:

The first one is the root ViewController, where the ScrollView is and the second one I want to add in the ScrollView

Try this and see:

self.scrollView.frame = CGRect( <set frame> )

var imgOne = UIImageView(frame: CGRect( <set frame> ))
var imgTwo = UIImageView(frame: CGRect( <set frame> ))
var vcView = UIView(frame: CGRect( <set frame> ))
addChildVC(vcView: vcView)

imgOne.image = UIImage(named: "preview1")
imgTwo.image = UIImage(named: "preview2")

self.scrollView.addSubview(imgOne)
self.scrollView.addSubview(imgTwo)
self.scrollView.addSubview(vcView)



self.scrollView.contentSize = CGSize( <set content size> )
self.scrollView.isPagingEnabled = true

Add child view Controller

func addChildVC(vcView: UIView){

let testVC = self.storyboard?.instantiateViewControllerWithIdentifier("testIdentifier") as! TestViewController
    testVC.view.frame = vcView.bounds
    vcView.addSubview(testVC.view)
    self.addChildViewController(testVC)
    testVC.didMoveToParentViewController(self)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM