How can I use swiftUI in my compose in compose mul...
# compose-ios
a
How can I use swiftUI in my compose in compose multiplatform? https://www.jetbrains.com/help/kotlin-multiplatform-dev/compose-ios-ui-integration.html#use-swiftui-inside-compose-multiplatform I checked this link but it used swiftUI view in ContentView.swift
a
Hey! It's definitely possible to use SwiftUI inside compose, by embedding UIHostingController (which is a child of UIViewController) in compose code using interop methods like
@Composable UIKitViewController()
. Could you please elaborate a bit regarding your problem?
a
as the example in link shows I have kotlin function
fun ComposeEntryPointWithUIView(createUIView: () -> UIView): UIViewController =
ComposeUIViewController {
Column(horizontalAlignment = Alignment.CenterHorizontally) {
UIKitView(
factory = createUIView,
modifier = Modifier
.size(300.dp)
.border(2.dp, Color.Blue),
)
}
}
but I couldn't call it from kotlin because it has lambda.
in the example this kotlin function is used in swift howeover I want to use it in kotlin, so I can call swiftUI views from compose functions
a
Okay, In Swift code you need to create subclass of
UIHostingController
with SwiftUI you needed, and pass this object to Kotlin Code in any way you want (Like factory interface, or just as a reference). Then you need to use
UIKitViewController()
instead of
UIKitView()
to place this controller on the compose scene.
a
I cant access my swift functions and classes from kotlin and all examples show accessing compose in swiftUI mostly
a
Yep, but you can pass reference of any Swift object to Kotlin code. Use interfaces defined in Kotlin code to achieve desired behaviour. Just make sure you are using correct application template, where the application execution starts from Swift code, but not from Kotlin.
a
I couldn't reference to swift object from kotlin. it is not accessible. if it is possible can you make a small project and share with me?
a
You don't need swift classes to be accessible there. But you can pass object:
Copy code
// Kotlin:
interface Factory {
    companion object {
        var shared: Factory? = null
    }
    fun makeController(): UIViewController
}

@Composable
fun MyView() {
    UIKitViewController(
        Factory.shared!!.makeController(),
        ...
    )
}

// Swift:
class TheFactory: Factory {
    func makeController() -> UIViewController {
        MySwiftUIViewController()
    }
}

class MySwiftUIViewController: UIHostingController { ... }

class AppDelegate: UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        FactoryCompanion().shared = TheFactory()
        ...
        return true
    }
}
a
thank you so much. it worked. I got the idea
👍 1
344 Views