Dato' Mohammad Nurdin Dato' Mohammad Nurdin - 6 months ago 146
iOS Question

Swift - How to link two view controllers into one container view and switch between them using segmented control?

Right now I got one view controller that contain 1 segmented control and 2 UI views. But I think it's too complicated to update the UI view for enhancement for future editing. I'm using hidden method.

import UIKit

class PopularHistoryViewController: UIViewController {


@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var popularView: UIView!
@IBOutlet weak var historyView: UIView!

@IBAction func indexChanged(sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex
{
case 0:
NSLog("Popular selected")
//show popular view
popularView.hidden = false
historyView.hidden = true
case 1:
NSLog("History selected")
//show history view
popularView.hidden = true
historyView.hidden = false
default:
break;
}
}

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

}


What i want is 1 container view that contain 2 controller views so I can switch them using segmented control.

enter image description here

Please advice.

Answer

I found the answer. Initiate UIView in viewDidLoad().

override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

        popularView.hidden = false
        historyView.hidden = true
    }