LifecycleHooks allows custom code to be injected into views and view controllers in response to lifecycle events, e.g.,
viewController.on(.viewDidAppear) { animated in
print("View did appear", animated)
}
The following lifecycle events are supported:
UIViewController
lifecycle hooks:
viewDidLoad
viewWillAppear
viewDidAppear
viewWillDisappear
viewDidDisappear
UIView
lifecycle hooks:
didMoveToWindow
NOTE: Actions are run after the object's own implementation of the respective methods, with the exception of viewDidLoad
, for which actions are run before the view controller's own viewDidLoad
implementation.
Lifecycle events are automatically passed on to a view controller's children (and a view's subviews). By adding an invisible view / view controller into the hierarchy, the custom code can be executed at appropriate points. This was inspired by this post by Soroush Khanlou.
The approach has been refined to avoid forcing the target view controller's view to be loaded prematurely when the hook is added. This is achieved by using KVO to monitor when the view loads. This is how the viewDidLoad
hook is implemented, and explains why that particular hook is run before viewDidLoad
is called.
In most circumstances subclassing is sufficient to add lifecycle-dependent code directly into a view / view controller without needing external code injection. However, there are some cases where this is not possible, e.g.:
UIViewController
extension.The following parameters allow for further customization of lifecycle hooks:
onceOnly
: Whether the hook should be performed once only or every time the lifecycle event is triggered.priority
: If you add multiple hooks for a particular lifecycle event, they occur in priority order, (or in the order they were added if the priorities are the same).cancel()
on the returned object.LifecycleHooks is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'LifecycleHooks'
Add the following to your Cartfile:
github "johnpatrickmorgan/LifecycleHooks"
Adding the following to the dependencies
array of your Package.swift
:
dependencies: [
.package(url: "https://github.com/johnpatrickmorgan/LifecycleHooks.git", from: "0.6.1")
]
LifecycleHooks is available under the MIT license. See the LICENSE file for more info.
link |
Stars: 90 |
Last commit: 3 years ago |
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics