Skip to content

Instantly share code, notes, and snippets.

@michalguspiel
Created March 15, 2024 11:59
Show Gist options
  • Save michalguspiel/9d0ae407ca7f2cd0234f6879a1f08290 to your computer and use it in GitHub Desktop.
Save michalguspiel/9d0ae407ca7f2cd0234f6879a1f08290 to your computer and use it in GitHub Desktop.
Swift UI in Compose Multiplatform
@main
struct iOSApp: App {
init() {
FactoryCompanion().shared = TheFactory()
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
interface Factory {
companion object {
var shared: Factory? = null
}
fun makeController(): UIViewController
}
@OptIn(ExperimentalForeignApi::class)
@Composable
fun MyView(modifier: Modifier = Modifier) {
UIKitViewController(
modifier = modifier,
factory = { Factory.shared!!.makeController() },
)
}
class TheFactory: Factory {
func makeController() -> UIViewController {
MySwiftUIViewController()
}
}
// Create your SwiftUI view
struct MySwiftUIView: View {
var body: some View {
Text("Hello, SwiftUI!")
}
}
// Subclass UIHostingController to create a custom SwiftUI view controller
class MySwiftUIViewController: UIHostingController<MySwiftUIView> {
// Optionally, you can add custom initialization or configuration here
// Example of custom initialization
init() {
super.init(rootView: MySwiftUIView())
setup()
}
// Example of custom configuration
func setup() {
// Add any custom setup code here
}
// Required initializer when subclassing UIHostingController
@objc required dynamic init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder, rootView: MySwiftUIView())
setup()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment