Skip to content

Commit

Permalink
Merge pull request #92 from iMostfa/feature/add-on-inject-hook-docs
Browse files Browse the repository at this point in the history
Pass host to onInjection Hook + Add docs
  • Loading branch information
krzysztofzablocki committed Apr 8, 2024
2 parents 1f368dc + 7345ab8 commit 838e614
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,23 @@ rootViewController.pushViewController(Inject.ViewControllerHost(viewController),
let viewController = Inject.ViewControllerHost(YourViewController())
rootViewController.pushViewController(viewController, animated: true)
```

> *Remember you **don't need** to remove this code when you are done, it's NO-OP in production builds.*

#### **Injection Hook for UIKit**
depending on the architecture used in your UIKit App, you might want to attach a hook to be executed each time a view controller is reloaded.

Eg. you might want to bind the `UIViewController` to the presenter each-time there's a reload, to achieve this you can use `onInjectionHook`
Example:

```swift
myView.onInjectionHook = { hostedViewController in
//any thing here will be executed each time the controller is reloaded
// for example, you might want to re-assign the controller to your presenter
presenter.ui = hostedViewController
}
```

#### iOS 12
You need to add -weak_framework SwiftUI to Other Linker Flags for iOS 12 to work.

Expand Down
16 changes: 14 additions & 2 deletions Sources/Inject/Integrations/Hosts.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,18 @@ public typealias ViewHost = _InjectableViewHost
open class _InjectableViewControllerHost<Hosted: InjectViewControllerType>: InjectViewControllerType {
public private(set) var instance: Hosted
let constructor: () -> Hosted
public var afterInjectionHook: (() -> Void)?
/// Attaches a hook to be executed each time after a controller is reloaded.
///
/// Usage:
/// ```swift
/// let myView = ViewControllerHost(TestViewController())
/// myView.onInjectionHook = { hostedViewController in
/// //any thing here will be executed each time the controller is reloaded
/// // for example, you might want to re-assign the controller to your presenter
/// presenter.ui = hostedViewController
/// }
/// ```
public var onInjectionHook: ((Hosted) -> Void)?

public init(_ constructor: @autoclosure @escaping () -> Hosted) {
instance = constructor()
Expand All @@ -34,8 +45,9 @@ open class _InjectableViewControllerHost<Hosted: InjectViewControllerType>: Inje

addAsChild()
onInjection { [weak self] instance in
guard let self else { return }
instance.resetHosted()
self?.afterInjectionHook?()
self.onInjectionHook?(self.instance)
}
}

Expand Down

0 comments on commit 838e614

Please sign in to comment.