【问题标题】:How to load a UIViewController inside an UIScrollView如何在 UIScrollView 中加载 UIViewController
【发布时间】:2017-02-17 13:36:09
【问题描述】:

这是我的设置。我的主视图控制器顶部有一个UIScrollView,我在其中加载了多个视图控制器。我还有一个添加按钮,它将使用 Push segue 呈现一个新的视图控制器。

我希望这个视图控制器也只加载到滚动视图的顶部,而不是整个屏幕。
到目前为止,我尝试了 2 种不同的方法,但都没有成功:

  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)
}

这两种解决方案都会使我的应用崩溃。
有没有办法正确实现这一点?

【问题讨论】:

标签: ios swift


【解决方案1】:

您不能在同一个视图控制器上推送任何视图控制器,您需要将容器视图添加到滚动视图。然后,如果您愿意,您可以在点击添加按钮时滚动滚动,这样看起来就像正在向其中添加新控制器。可以这样做,

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)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 1970-01-01
    • 2011-01-07
    • 2014-08-18
    • 2019-06-05
    • 2023-03-28
    相关资源
    最近更新 更多