Reputation: 127
I want to create a container View programmatically that has inside a bunch of view controllers. I have a segmented controller that when the user tapped a button it should display a certain viewController without doing a segue. I have everything inside a ViewController, I wanted to know how to properly make the segmented controller display a certain view controller when tapped.
func setUpSegmentedControl() {
let seg = UISegmentedControl(items: ["1", "2", "3"])
seg.selectedSegmentIndex = 0
seg.translatesAutoresizingMaskIntoConstraints = false
seg.layer.cornerRadius = 8
seg.backgroundColor = UIColor.white
seg.addTarget(self, action: #selector(changeColor(sender:)), for: .valueChanged)
view.addSubview(seg)
NSLayoutConstraint.activate([
seg.centerXAnchor.constraint(equalTo: view.centerXAnchor), seg.centerYAnchor.constraint(equalTo: view.centerYAnchor), seg.leadingAnchor.constraint(equalTo: view.leadingAnchor), seg.trailingAnchor.constraint(equalTo: view.trailingAnchor), seg.heightAnchor.constraint(equalToConstant: 50)
])
}
@objc func changeColor(sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
addChild(FirstViewController())
print("1")
case 1:
addChild(SecondViewController())
print("2")
default:
addChild(ThirdViewController())
print("3")
}
}
Upvotes: 0
Views: 100
Reputation: 1568
To add a view controller to a container view programmatically, you need to call addSubview
and didMove
in addition to addChild
.
let firstViewController = FirstViewController()
addChild(firstViewController)
firstViewController.view.translatesAutoresizingMaskIntoConstraints = false
containerView.addSubview(firstViewController.view) // replace `containerView` with the name of the view that's supposed to contain the VC's view
// add constraints or set frame manually
let trailingConstraint = firstViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor)
let leadingConstraint = firstViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor)
let topConstraint = firstViewController.view.topAnchor.constraint(equalTo: view.topAnchor)
let bottomConstraint = firstViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)
NSLayoutConstraint.activate([trailingConstraint, leadingConstraint, topConstraint, bottomConstraint])
firstViewController.didMove(to parent: self)
If you want to remove a child view controller programatically:
let child = children.first // or other way to identify your VC
child?.willMove(toParentViewController: nil)
child?.view.removeFromSuperview()
child?.view.removeFromParentViewController()
Upvotes: 1