How to load a UIViewController inside an UIScrollView

前端 未结 1 1857
别那么骄傲
别那么骄傲 2021-01-03 07:12

This is my setup. I have an UIScrollView on top of my main view controller in which I load multiple view controllers. I also have an Add button which will prese

相关标签:
1条回答
  • 2021-01-03 07:43

    You cannot push any view controller on the same view controller, you need to add container view to your scroll view. And then if you want you may scroll the scroll on tap of the add button, so that it will seem like new controller is being added to it. It can be done like this,

    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)
    

    You may want to disable scroll of your scroll view if you want just to add(move) to another view controller only by your add button.

    0 讨论(0)
提交回复
热议问题