Created
March 15, 2024 11:59
-
-
Save michalguspiel/9d0ae407ca7f2cd0234f6879a1f08290 to your computer and use it in GitHub Desktop.
Swift UI in Compose Multiplatform
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@main | |
struct iOSApp: App { | |
init() { | |
FactoryCompanion().shared = TheFactory() | |
} | |
var body: some Scene { | |
WindowGroup { | |
ContentView() | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() }, | |
) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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