Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. import UIKit
  2.  
  3. final class StackViewController: UIViewController {
  4.  
  5. private let stackView: UIStackView = {
  6. let stackView = UIStackView()
  7. stackView.axis = .vertical
  8. stackView.alignment = .fill
  9. stackView.distribution = .fill
  10. stackView.spacing = 5
  11. return stackView
  12. }()
  13.  
  14. private var contents:[UIViewController]
  15. private var portraitConstraints = [NSLayoutConstraint]()
  16.  
  17. init(content:[UIViewController]) {
  18. self.contents = content
  19. super.init(nibName: nil, bundle: nil)
  20. }
  21.  
  22. required init?(coder aDecoder: NSCoder) {
  23. fatalError("init(coder:) has not been implemented")
  24. }
  25.  
  26. override func loadView() {
  27. view = stackView
  28. add(contents: contents)
  29. setConstraints(contents:contents)
  30. }
  31.  
  32. private func add(contents:[UIViewController]){
  33. for content in contents {
  34. stackView.addArrangedSubview(content.view)
  35. }
  36. }
  37.  
  38. private func setConstraints(contents:[UIViewController]) {
  39. for content in contents {
  40. addConstraints(content)
  41. }
  42. }
  43.  
  44. private func addConstraints(_ content:UIViewController) {
  45.  
  46. let contentSize = content.view.frame.size
  47. var height = contentSize.height
  48. var width = contentSize.width
  49.  
  50. if content.preferredContentSize != .zero {
  51. let size = content.preferredContentSize
  52. height = size.height
  53. width = size.width
  54. }
  55.  
  56. portraitConstraints.append(contentsOf: [
  57. content.view.heightAnchor.constraint(equalToConstant: height),
  58. content.view.widthAnchor.constraint(equalToConstant: width)
  59. ])
  60.  
  61. _ = portraitConstraints.map{ $0.priority = .defaultHigh }
  62. updateStackViewAxis()
  63. }
  64.  
  65. override func viewDidLoad() {
  66. super.viewDidLoad()
  67. title = "Stack View"
  68. }
  69.  
  70. private func updateStackViewAxis() {
  71. switch UIDevice.current.orientation {
  72. case .landscapeLeft, .landscapeRight:
  73. stackView.axis = .horizontal
  74. default:
  75. stackView.axis = .vertical
  76. if portraitConstraints.isEmpty {
  77. setConstraints(contents: contents)
  78. }
  79. NSLayoutConstraint.activate(portraitConstraints)
  80. }
  81. }
  82.  
  83. /* change the stackviews axis when the device rotates */
  84. override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
  85. updateStackViewAxis()
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement