在 Xcode6 中使用适用于 iOS8 的 Swift,我需要创建一个 ScrollView 来滚动动态创建的卡片。这些卡片包含自己独特的图像、文本和按钮功能,但布局相同。我无法理解如何在 Storyboard 中创建一个可重复使用的 View Controller ,我可以从中构建每张卡片,然后将它们全部嵌入到 ScrollView 容器中,以便我可以一次滑过它们。
通常我喜欢在 Stack Overflow 上询问更具体的问题,但经过数小时的研究后我不知所措;非常感谢您的帮助!
最佳答案
您正在寻找自定义容器 View Controller 。
如果以编程方式执行此操作,则在父 Controller 上调用 addChildViewController
(从而将 subview Controller 添加到 View Controller 层次结构中),完成 subview 的所有配置(包括将其添加到父 Controller 的 View 层次结构),然后在最后,对子 Controller 调用 didMoveToParentViewController
:
let child = storyboard!.instantiateViewController(withIdentifier: "storyboardIdForChildScene")
addChild(child)
child.view.frame = .zero
scrollView.addSubview(child.view)
child.didMove(toParent: self)
当以编程方式删除时,您可以反转此过程,对 subview 调用 willMoveToParentViewController:nil
,从其父 View 中删除 subview ,完成后,调用 removeFromParentViewController
:
child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()
如果在 Interface Builder 中执行此操作,则更容易,只需将“容器 View ”从“对象库”拖到父 View Controller 的场景中即可:
有关如何执行此操作的更多信息,请参阅 Implementing a Custom Container View Controller在 View Controller Programming Guide 中。有关执行这些包含调用以使 View Controller 层次结构与 View 层次结构保持同步的重要性的讨论,请参见 WWDC 2011 视频 Implementing UIViewController Containment .
以上内容适用于 Swift 4。对于早期的 Swift 版本,请参阅 previous revision of this answer .
关于ios - 在 ScrollView 中重用 View Controller 。 swift iOS8开发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430225/