如何正确地使包含某些viewControllers的容器视图(以编程方式)?

时间:2019-05-15 18:42:05

标签: ios swift

我想以编程方式创建一个容器View,该容器View内有许多视图控制器。我有一个分段的控制器,当用户点击一个按钮时,它应该显示某个viewController而不进行选择。 我把所有东西都放在ViewController中, 我想知道如何在点击时使分段控制器正确显示某个视图控制器。

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")
    }
}

1 个答案:

答案 0 :(得分:1)

要以编程方式将视图控制器添加到容器视图中,除了addSubview之外,还需要调用didMoveaddChild

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)

如果要以编程方式删除子视图控制器:

let child = children.first // or other way to identify your VC
child?.willMove(toParentViewController: nil)
child?.view.removeFromSuperview()
child?.view.removeFromParentViewController()

Example project