Skip to content

Instantly share code, notes, and snippets.

@asobolevsky
Created June 6, 2020 11:06
Show Gist options
  • Save asobolevsky/4c5d9d887a652d135907d8b76fdc99b2 to your computer and use it in GitHub Desktop.
Save asobolevsky/4c5d9d887a652d135907d8b76fdc99b2 to your computer and use it in GitHub Desktop.
typealias BehaviorClosure = (_ viewController: UIViewController) -> ()
enum ViewControllerLifecycle : CaseIterable {
typealias AllCases = [ViewControllerLifecycle]
case afterLoading(BehaviorClosure?)
case afterAppearing(BehaviorClosure?)
case beforeAppearing(BehaviorClosure?)
case beforeDisappearing(BehaviorClosure?)
case afterDisappearing(BehaviorClosure?)
case beforeLayingOutSubviews(BehaviorClosure?)
case afterLayingOutSubviews(BehaviorClosure?)
static var allCases: [ViewControllerLifecycle] {
return [afterLoading(nil),
beforeAppearing(nil),
beforeDisappearing(nil),
beforeLayingOutSubviews(nil),
afterLayingOutSubviews(nil)]
}
}
func createAnonimousBehavior(with lifecycle: [ViewControllerLifecycle]) -> ViewControllerLifecycleBehavior {
class AnonimousBehavior: ViewControllerLifecycleBehavior {
private var lifeCycle: [ViewControllerLifecycle]
init(lifeCycle:[ViewControllerLifecycle]) {
self.lifeCycle = lifeCycle
}
func afterLoading(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .afterLoading(let closure) = $0 else { return }
closure?(viewController)
}
}
func afterAppearing(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .afterAppearing(let closure) = $0 else { return }
closure?(viewController)
}
}
func beforeAppearing(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .beforeAppearing(let closure) = $0 else { return }
closure?(viewController)
}
}
func beforeDisappearing(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .beforeDisappearing(let closure) = $0 else { return }
closure?(viewController)
}
}
func afterDisappearing(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .afterDisappearing(let closure) = $0 else { return }
closure?(viewController)
}
}
func beforeLayingOutSubviews(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .beforeLayingOutSubviews(let closure) = $0 else { return }
closure?(viewController)
}
}
func afterLayingOutSubviews(_ viewController: UIViewController) {
lifeCycle.forEach {
guard case .afterLayingOutSubviews(let closure) = $0 else { return }
closure?(viewController)
}
}
}
let behavior = AnonimousBehavior(lifeCycle: ViewControllerLifecycle.allCases)
return behavior
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment