Files
2021-09-24 01:33:53 +06:00

81 lines
2.7 KiB
Swift

//
// BaseViewController.swift
// PrivadoVPN
//
// Created by Zhandos Bolatbekov on 03.06.2021.
// Copyright © 2021 Privado LLC. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController, ReactivelyConstrained {
var portraitConstraints = [NSLayoutConstraint]()
var landscapeConstraints = [NSLayoutConstraint]()
var sharedConstraints = [NSLayoutConstraint]()
let layoutEmitter = Emitter<EmitterLayoutChangeType>()
// MARK: - Init
init() {
super.init(nibName: nil, bundle: nil)
self.layoutEmitter.addReaction { [weak self] isLandscape -> ShouldContinueReceiveNotifications in
guard let self = self else { return false }
if isLandscape {
NSLayoutConstraint.deactivate(self.portraitConstraints)
NSLayoutConstraint.activate(self.landscapeConstraints)
} else {
NSLayoutConstraint.deactivate(self.landscapeConstraints)
NSLayoutConstraint.activate(self.portraitConstraints)
}
NSLayoutConstraint.activate(self.sharedConstraints)
self.layoutChildren(for: self, isLanscape: isLandscape)
self.layoutSubViews(for: self.view, isLandscape: isLandscape)
self.updateViewConstraints()
return true
}
}
func layoutSubViews(for view: UIView, isLandscape: Bool) {
view.subviews.forEach { view in
if let view = view as? BaseView {
view.layoutEmitter.invoke(isLandscape)
view.layoutIfNeeded()
}
}
}
func layoutChildren(for controller: BaseViewController, isLanscape: Bool) {
controller.children.forEach { vc in
if let vc = vc as? BaseViewController {
vc.layoutEmitter.invoke(isLanscape)
vc.updateViewConstraints()
}
}
}
func layoutForCurrentOrientation() {
let landscape = DeviceInfoProvider.isLandscapeOrienation && self.view.bounds.width * 3 >= UIScreen.main.bounds.width * 2
self.layoutEmitter.invoke(landscape)
}
@available(*, unavailable)
required init?(coder: NSCoder) { nil }
// MARK: - Lifecycle
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let isLandscape = DeviceInfoProvider.isLandscapeOrienation && size.width * 3 >= UIScreen.main.bounds.width * 2
self.layoutEmitter.invoke(isLandscape)
self.view.subviews
.compactMap { $0 as? ReactivelyConstrained }
.forEach { $0.layoutEmitter.invoke(isLandscape) }
}
}