Skip to content

Instantly share code, notes, and snippets.

@damodarnamala
Created July 31, 2023 07:29
Show Gist options
  • Save damodarnamala/f2c30e115db84b5b4f843b5b8c77010b to your computer and use it in GitHub Desktop.
Save damodarnamala/f2c30e115db84b5b4f843b5b8c77010b to your computer and use it in GitHub Desktop.
iOS adding child view controllers in Container View
class ContainerViewController: UIViewController {
private lazy var contentStackView: UIStackView = {
let view = UIStackView()
view.axis = .vertical
view.spacing = 16.0
return view
}()
override func loadView() {
let mainView = UIView()
mainView.addSubview(self.contentStackView)
let views = [SecondViewController(), ThirdViewController()]
_ = views.map { child in
child.willMove(toParent: self)
addChild(child)
contentStackView.addArrangedSubview(child.view)
child.didMove(toParent: self)
}
self.view = mainView
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
contentStackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
contentStackView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 16),
contentStackView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -16),
contentStackView.topAnchor.constraint(equalTo: self.view.topAnchor, constant: 16),
contentStackView.bottomAnchor.constraint(lessThanOrEqualTo: self.view.bottomAnchor, constant: -16)
])
}
public init() {
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func show() {
let continer = ContainerViewController()
self.present(continer, animated: true)
}
}
class SecondViewController: UIViewController {
var blackView: UIView = {
let view = UIView()
view.backgroundColor = .black
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(blackView)
blackView.snp.makeConstraints { make in
make.edges.leading.trailing.top.equalToSuperview()
make.height.equalTo(100)
}
}
public init() {
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
}
class ThirdViewController: UIViewController {
var redView: UIView = {
let view = UIView()
view.backgroundColor = .red
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(redView)
redView.snp.makeConstraints { make in
make.edges.leading.trailing.top.equalToSuperview()
make.height.equalTo(100)
}
}
public init() {
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment