如何在UIScrollView中加载UIViewController

这是我的设置。 我有一个UIScrollView在我的主视图控制器的顶部我加载多个视图控制器。 我也有一个添加button,将呈现一个新的视图控制器使用Push塞格。

我希望这个视图控制器也只加载滚动视图的顶部,而不是所有的屏幕。
到现在为止,我尝试了两种不同的东西,但都没有做任何工作:

  1. prepareForSegue滚动视图中添加视图控制器:

      override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let addViewController = segue.destination as! AddViewController addChildViewController(addViewController) addViewController.view.frame = CGRect(x: 0, y: 0, width: width, height: height) scrollView.addSubview(addViewController.view) didMove(toParentViewController: self) } 
  2. 在UIButton动作中添加视图控制器:

@IBAction func addDidTouch(_ sender:AnyObject){

  let addViewController = AddViewController() addChildViewController(addViewController) addViewController.view.frame = CGRect(x: 0, y: 0, width: width, height: height) scrollView.addSubview(addViewController.view) didMove(toParentViewController: self) } 

这两个解决scheme崩溃我的应用程序。
有没有一种方法来正确实施?

您不能在同一个视图控制器上推送任何视图控制器,您需要将容器视图添加到您的滚动视图。 然后如果你想要的话,你可以滚动添加button的水龙头滚动,这样看起来像新的控制器正在被添加到它。 可以这样做,

 scrollView.contentSize = CGSize(width: screenWidth*3, height: 1) let first = getStoryboard(StoryboardName.Main).instantiateViewControllerWithIdentifier("FirstViewController") as! FirstViewController let second = getStoryboard(StoryboardName.Main).instantiateViewControllerWithIdentifier("SecondViewController") as! SecondViewController let third = getStoryboard(StoryboardName.Main).instantiateViewControllerWithIdentifier("ThirdViewController") as! ThirdViewController self.addChildViewController(first) self.scrollView.addSubview(first.view) first.willMoveToParentViewController(self) self.addChildViewController(second) self.scrollView.addSubview(second.view) second.willMoveToParentViewController(self) self.addChildViewController(third) self.scrollView.addSubview(third.view) third.willMoveToParentViewController(self) first.view.frame.origin = CGPointZero second.view.frame.origin = CGPoint(x: screenWidth, y: 0) third.view.frame.origin = CGPoint(x: 2*screenWidth, y: 0) 

如果您只想通过添加button添加(移动)到另一个视图控制器,则可能需要禁用滚动视图的滚动。