Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

garyon wong
garyon wong
10,379 Points

Swift: How do I make the child view preload the data which was passed from parent view?

Hi all,

I am implementing a parent view which contains segmented control which controls a content view to swap between child views.

My issue is the function only triggers when I switch the view so data was not loaded to the "default" view. Should I do anything with loadview()?

@IBAction func segmentSwitch(sender: UISegmentedControl) {

    switch sender.selectedSegmentIndex {
    case 0:
        var newController = storyboard?.instantiateViewControllerWithIdentifier(viewControllerIdentifiers[sender.selectedSegmentIndex]) as ServiceViewController
        let oldController = childViewControllers.last as UIViewController

        oldController.willMoveToParentViewController(nil)
        addChildViewController(newController)
        newController.view.frame = oldController.view.frame

        transitionFromViewController(oldController, toViewController: newController, duration: 0.25, options: .TransitionCrossDissolve, animations: { () -> Void in }, completion: { (finished) -> Void in
            oldController.removeFromParentViewController()
            newController.didMoveToParentViewController(self)
            newController.serviceLabel00.text = "FIRST"
            newController.service = self.service

        })
        case 1:
        .......
        default: 
        break}

Thanks, Garyon

need2edit
need2edit
Courses Plus Student 12,848 Points

If I am understanding your question correctly, you want to have the child view load the default view synced up with the segmentedControl's default state. Here is one possibility I've used on a project in the past. First add your segmented control as an @IBOutlet. On viewDidLoad or viewWillLoad you can pass this outlet to the segmented control as the sender. This is like you tapping it, but instead you're calling it in code. It might look like this:

viewDidLoad() {
       segmentSwitch(sender: self.mySegmentedControl)  
     // This calls your function, and would set child view to the default state of the segmentedControl

}

Please let me know if I'm understanding things correctly and this is a solution that works for you.

1 Answer

garyon wong
garyon wong
10,379 Points

Hi need2edit,

Yes, this is exactly what I want and it works.

Thanks!

Garyon