swiftuicontainerviewchildviewcontroller

how to load child view controllers or container views - Swift


containerView

I don't have a problem displaying each container view when switching between them using the segmented controller. What I do have a problem with is that whenever the parent view loads, both the blue and green container views also load.

I want the blue to load with the parent view controller and the green to load only when I switch the segmented control. Any Ideas?

override fund viewDidload() {
super.viewdidload()

   let child = GreenViewController()
   addChild(child)
   child.view.frame = frame
   view.addSubview(child.view)
   child.didMove(toParent: self)
}

I tried using the code above, but it doesn't seem to make a difference as loading for both child view controllers still load once the parent loads


Solution

  • As i understand there are 2 container views and you want to see the blue view when the segmented is first and you want to see the green view when the segmented is second if it is true the solution is like this;

    You should init the uivew(hold on the ctrl and drag it to viewcontroller for both blue and green container view)(you need to add 2 different container view) and write

    if segmented.selectedIndex == 0 { 
    
        greenView.isHidden = true
        blueView.isHidden = false
    
    } else if segmented.selectedIndex == 1 {
    
        greenView.isHidden = false
        blueView.isHidden = true
    }