Skip to content

Instantly share code, notes, and snippets.

@mredig
Created April 13, 2021 02:48
Show Gist options
  • Save mredig/f64f92443dc2392d7d6d4a6cf0574271 to your computer and use it in GitHub Desktop.
Save mredig/f64f92443dc2392d7d6d4a6cf0574271 to your computer and use it in GitHub Desktop.
// This causes a retain cycle on `vc`
var vc: UIViewController?
let myNewSUIView = ASwiftUIView(
completion: { url in
vc?.dismiss(animated: true)
})
let hostingController = UIHostingController(rootView: myNewSUIView)
let parentContainerVC = ParentContainerViewController(rootViewController: hostingController)
vc = parentContainerVC
present(vc, animated: true)
// I tried this:
completion: { [weak vc] url in
// however, that captures `vc` prior to having been set, meaning it will be `nil` when executed.
// What I came up with was this:
class WeakCapture<T: AnyObject> {
weak var value: T?
init(value: T) {
self.value = value
}
init(type: T.Type) {
self.value = nil
}
}
// combined with
let weakVC = WeakCapture(type: UIViewController.self)
let myNewSUIView = ASwiftUIView(
completion: { url in
weakVC.value?.dismiss(animated: true)
})
let hostingController = UIHostingController(rootView: myNewSUIView)
let parentContainerVC = ParentContainerViewController(rootViewController: hostingController)
weakVC.value = parentContainerVC
// So my question is - is there a better way to have a weak reference to the SwiftUI View's hosting controller to dismiss from a button press inside the View?
@mredig
Copy link
Author

mredig commented Apr 13, 2021

Context: this is taking place in a Coordinator with a one off SwiftUI view in a UIKit app.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment