Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing view controller inside of scroll view. Swift iOS8 development

Using Swift for iOS8 in Xcode6, I need to create a scroll view that will scroll through dynamically created cards. The cards contain their own unique images, text, and button functions but share an identical layout. I'm having trouble understanding how to create a re-usable view controller in the storyboard from which I can build each card and then embed them all into a scroll view container so that I can slide through them one at a time.

Normally I like to ask more specific questions on Stack Overflow but after hours of research I'm at a loss; your help would be much appreciated!

like image 600
madeFromCode Avatar asked Oct 17 '14 17:10

madeFromCode


1 Answers

You're looking for custom container view controller.

If doing this programmatically, you call addChildViewController on the parent controller (thereby adding the child view controller into the view controller hierarchy), do all of the configuration of the child's view (including adding it to the parent controller's view hierarchy) and then at the very end, call didMoveToParentViewController on the child:

let child = storyboard!.instantiateViewController(withIdentifier: "storyboardIdForChildScene")
addChild(child)
child.view.frame = .zero
scrollView.addSubview(child.view)
child.didMove(toParent: self)

When removing programmatically, you reverse this process, calling willMoveToParentViewController:nil on the child, remove the child view from its superview, and when all done, call removeFromParentViewController:

child.willMove(toParent: nil)
child.view.removeFromSuperview()
child.removeFromParent()

If doing this in Interface Builder, it's much easier, just drag the "Container View" from the "Object Library" onto your parent view controller's scene:

container view

For more information on how to do this, see Implementing a Custom Container View Controller in the View Controller Programming Guide. For a discussion on why it's important to do these containment calls in order to keep the view controller hierarchy synchronized with the view hierarchy, see WWDC 2011 video Implementing UIViewController Containment.


The above is for Swift 4. For early Swift versions, see previous revision of this answer.

like image 123
Rob Avatar answered Sep 27 '22 23:09

Rob