Skip to content

Instantly share code, notes, and snippets.

@dkw5877
Last active April 12, 2019 21:54
Show Gist options
  • Save dkw5877/4fbef389ee87184a3eb38f122e5c51a4 to your computer and use it in GitHub Desktop.
Save dkw5877/4fbef389ee87184a3eb38f122e5c51a4 to your computer and use it in GitHub Desktop.
Example of UIViewController who's main view has been replaced by a UIStackView
import UIKit
final class StackViewController: UIViewController {
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .fill
stackView.spacing = 5
return stackView
}()
private var contents:[UIViewController]
private var portraitConstraints = [NSLayoutConstraint]()
init(content:[UIViewController]) {
self.contents = content
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = stackView
add(contents: contents)
setConstraints(contents:contents)
}
private func add(contents:[UIViewController]){
for content in contents {
stackView.addArrangedSubview(content.view)
}
}
private func setConstraints(contents:[UIViewController]) {
for content in contents {
addConstraints(content)
}
}
private func addConstraints(_ content:UIViewController) {
let contentSize = content.view.frame.size
var height = contentSize.height
var width = contentSize.width
if content.preferredContentSize != .zero {
let size = content.preferredContentSize
height = size.height
width = size.width
}
portraitConstraints.append(contentsOf: [
content.view.heightAnchor.constraint(equalToConstant: height),
content.view.widthAnchor.constraint(equalToConstant: width)
])
_ = portraitConstraints.map{ $0.priority = .defaultHigh }
updateStackViewAxis()
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Stack View"
}
private func updateStackViewAxis() {
switch UIDevice.current.orientation {
case .landscapeLeft, .landscapeRight:
stackView.axis = .horizontal
default:
stackView.axis = .vertical
if portraitConstraints.isEmpty {
setConstraints(contents: contents)
}
NSLayoutConstraint.activate(portraitConstraints)
}
}
/* change the stackviews axis when the device rotates */
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
updateStackViewAxis()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment