这是我的设置。我有一个UIScrollView
在我的主视图控制器之上,我在其中加载多个视图控制器。我还有一个“添加”按钮,它将使用 Push segue 呈现一个新的视图控制器。
我希望这个视图控制器也只加载在滚动视图的顶部,而不是整个屏幕。
到目前为止,我尝试了两种不同的方法,但都不起作用:
-
在滚动视图中添加视图控制器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)
}
在 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)
}
这两个解决方案都会使我的应用程序崩溃。
有没有办法正确地实现这一点?
您不能在同一个视图控制器上推送任何视图控制器,您需要将容器视图添加到滚动视图中。然后,如果您愿意,您可以点击添加按钮滚动滚动条,这样看起来就像正在向其中添加新控制器。可以这样做,
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)
如果您只想通过添加按钮添加(移动)到另一个视图控制器,您可能需要禁用滚动视图的滚动。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)