2016-11-18 120 views
1

如何將現有的視圖控制器添加到滾動視圖中。我已經嘗試了'viewDidLoad'內的下面的代碼,但它沒有工作。謝謝將視圖控制器並排添加到滾動視圖中

let view1 = ViewController6() 
     let view2 = ViewController2() 
     let view3 = ViewController3() 

     contentView.addSubview(view1) 
     contentView.addSubview(view2) 
     contentView.addSubview(view3) 

     self.contentView.contentSize = CGSize(width: self.view.frame.width * 3, height: self.view.frame.height) 
+0

看一看容器的觀點。這個想法是你創建一個contentView(UIView),將子UIViewControllers添加到當前的ViewController,然後將子ViewController的視圖添加到內容視圖中。 – uti0mnia

回答

0

檢查此代碼在這裏,我正在做你想要的東西。

func setupScrollView() 
    { 
     //loop for 
     for i in 0..<3 { 
      //we instantiate our viewController from storyboard 
      let news2 = self.storyboard?.instantiateViewController(withIdentifier: "NewsMasterViewController") as! NewsMasterViewController 
      //we adjust the frame according 
      news2.view.frame = CGRect(x: CGFloat(i) * self.scrollView.frame.size.width + CGFloat(MasterViewController.margin), y: 0, width: self.scrollView.frame.size.width - CGFloat(MasterViewController.margin * 2), height: self.scrollView.frame.size.height) 
      //we call layoutSubviews for constraints adjustments 
      news2.view.layoutSubviews() 
      self.addChildViewController(news2) 
      //added the view of my viewController "news2" to scrollView 
      self.scrollView.addSubview(news2.view) 
      news2.didMove(toParentViewController: self) 
      //added the viewController "news2" to my array of viewControllers 
      newsMasterViewControllers.append(news2) 
     } 

     //adjusted contentSize of scrollView according the number of viewControllers added 
     self.scrollView.contentSize = CGSize(width: self.view.frame.size.width * 3, height: self.scrollView.frame.size.height); 
    } 

我希望這有助於你

相關問題