When adding a child view controller you are always required to call addChild(_:) on the parent VC and didMove(toParent:) on the child VC.
let searchViewController = SearchViewController()
addChild(viewController)
searchViewController.didMove(toParent: self)
view.addSubview(searchViewController.view)
But the most important thing is that you are not constraining the SearchViewController
view at all in your ViewController
view
NSLayoutConstraint.activate([
searchViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
searchViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
searchViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
searchViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
And your final ViewController
implementation should look like this:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let searchViewController = SearchViewController()
addChild(viewController)
searchViewController.didMove(toParent: self)
view.addSubview(searchViewController.view)
searchViewController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
searchViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
searchViewController.view.topAnchor.constraint(equalTo: view.topAnchor),
searchViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
searchViewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
}
Another issue is that you are using old API for setting the constraints inside the SearchViewController
. The documentation of addConstraint says:
When developing for iOS 8.0 or later, set the constraint’s isActive property to true instead of calling the addConstraint method directly. The isActive property automatically adds and removes the constraint from the correct view.
You can use the activate(_:) static function on NSLayoutConstraint
to activate them at once.
view.addSubview(textField)
NSLayoutConstraint.activate([
textField.leadingAnchor
.constraint(equalTo: view.leadingAnchor, constant: 0),
textField.topAnchor
.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 0),
textField.trailingAnchor
.constraint(equalTo: view.trailingAnchor, constant: 0),
])
Resources:
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…