Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bjtitus/bbcb100fee16711a0e20c5387cba649d to your computer and use it in GitHub Desktop.
Save bjtitus/bbcb100fee16711a0e20c5387cba649d to your computer and use it in GitHub Desktop.
import UIKit
class ViewController: UIViewController {
private(set) var bottomBarLayoutGuide = UILayoutGuide()
private var redBox: UIView!
override func viewDidLoad() {
super.viewDidLoad()
view.addLayoutGuide(bottomBarLayoutGuide)
// Trying to migrate some old frame based code to Auto Layout
redBox = UIView()
redBox.backgroundColor = .systemRed
redBox.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(redBox)
NSLayoutConstraint.activate([
redBox.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 50.0),
redBox.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -50.0),
redBox.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
redBox.heightAnchor.constraint(equalToConstant: 50.0),
bottomBarLayoutGuide.bottomAnchor.constraint(equalTo: redBox.topAnchor)
])
let childViewController = ViewControllerB()
childViewController.view.frame = view.bounds
addChild(childViewController)
view.addSubview(childViewController.view)
childViewController.didMove(toParent: self)
view.backgroundColor = .systemBackground
}
}
class ViewControllerB: UIViewController {
init() {
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) { fatalError("\(#file) does not implement coder.") }
private lazy var greenBox: UIView = {
let greenBox = UIView()
greenBox.backgroundColor = .systemGreen
greenBox.translatesAutoresizingMaskIntoConstraints = false
return greenBox
}()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .clear
view.addSubview(greenBox)
NSLayoutConstraint.activate([
greenBox.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 50.0),
greenBox.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -50.0),
greenBox.heightAnchor.constraint(equalToConstant: 50.0)
])
}
private var greenBoxBottomConstraint: NSLayoutConstraint?
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
resetGreenBoxBottomConstraint(parent: parent)
}
func resetGreenBoxBottomConstraint(parent: UIViewController?) {
greenBoxBottomConstraint?.isActive = false
if let layoutGuide = (parent as? ViewController)?.bottomBarLayoutGuide {
greenBoxBottomConstraint = greenBox.bottomAnchor.constraint(equalTo: layoutGuide.topAnchor)
} else {
greenBoxBottomConstraint = greenBox.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
}
greenBoxBottomConstraint?.isActive = true
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment