Skip to content

Instantly share code, notes, and snippets.

@mycroftcanner
Created October 21, 2019 00:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mycroftcanner/501ec84c2621a1248c15fbb2ea50f675 to your computer and use it in GitHub Desktop.
Save mycroftcanner/501ec84c2621a1248c15fbb2ea50f675 to your computer and use it in GitHub Desktop.
Wraps a SwiftUI View inside a ASDisplayNode
//
// HostingNode.swift
//
import AsyncDisplayKit
import SwiftUI
class HostingNode: ASDisplayNode {
var viewController: UIViewController?
override init() {
super.init()
setViewBlock { [weak self]() -> UIView in
self?.viewController = self?.makeHostingController()
return self?.viewController?.view ?? UIView()
}
}
private func makeHostingController() -> UIViewController {
UIHostingController(
rootView: Text("Attention")
)
}
}
@mycroftcanner
Copy link
Author

Wrapping a SwiftUI View inside a ASDisplayNode

We can initialize a node and provide a SwiftUI view to be used as the backing view.

The Text view nests in a UIHostingController, aUIViewControllersubclass that represents a SwiftUI view within UIKit contexts.

The view is provided via a block that will return a view so that the actual construction of the view can be saved until later. The node display step happens synchronously because a node can only be asynchronously displayed when it wraps an _ASDisplayView (the internal view subclass), not when it wraps a UIView.

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