Kotlin Multiplatform Development Help

与 UIKit 框架的集成

Compose Multiplatform 可与 UIKit 框架互操作。您可以将 Compose Multiplatform 嵌入到 UIKit 应用程序中,也可以在 Compose Multiplatform 中嵌入原生 UIKit 组件。本页提供了在 UIKit 应用程序中使用 Compose Multiplatform 以及在 Compose Multiplatform UI 中嵌入 UIKit 组件的示例。

在 UIKit 应用程序中使用 Compose Multiplatform

要在 UIKit 应用程序中使用 Compose Multiplatform,请将您的 Compose Multiplatform 代码添加到任何 容器视图控制器 。以下示例在 UITabBarController 类中使用 Compose Multiplatform:

let composeViewController = Main_iosKt.ComposeOnly() composeViewController.title = "UIKit 中的 Compose Multiplatform" let anotherViewController = UIKitViewController() anotherViewController.title = "UIKit" // 设置 UITabBarController let tabBarController = UITabBarController() tabBarController.viewControllers = [ // 将创建的 ViewController 包装在 UINavigationController 中以设置标题 UINavigationController(rootViewController: composeViewController), UINavigationController(rootViewController: anotherViewController) ] tabBarController.tabBar.items?[0].title = "Compose" tabBarController.tabBar.items?[1].title = "UIKit"

使用此代码后,您的应用程序应如下所示:

UIKit

示例项目 中探索此代码。

在 Compose Multiplatform 中使用 UIKit

要在 Compose Multiplatform 中使用 UIKit 元素,请将您想要使用的 UIKit 元素添加到 Compose Multiplatform 的 UIKitView 。您可以完全使用 Kotlin 编写此代码,也可以使用 Swift。

在此示例中,UIKit 的 MKMapView 组件显示在 Compose Multiplatform 中。通过使用 Compose Multiplatform 的 Modifier.size()Modifier.fillMaxSize() 函数设置组件大小:

UIKitView( factory = { MKMapView() }, modifier = Modifier.size(300.dp), )

使用此代码后,您的应用程序应如下所示:

MapView

现在,让我们看一个高级示例。以下代码将 UIKit 的 UITextField 包装在 Compose Multiplatform 中:

@OptIn(ExperimentalForeignApi::class) @Composable fun UseUITextField(modifier: Modifier = Modifier) { var message by remember { mutableStateOf("Hello, World!") } UIKitView( factory = { val textField = object : UITextField(CGRectMake(0.0, 0.0, 0.0, 0.0)) { @ObjCAction fun editingChanged() { message = text ?: "" } } textField.addTarget( target = textField, action = NSSelectorFromString(textField::editingChanged.name), forControlEvents = UIControlEventEditingChanged ) textField }, modifier = modifier.fillMaxWidth().height(30.dp), update = { textField -> textField.text = message } ) }

factory 参数包含 editingChanged() 函数和 textField.addTarget() 监听器,用于检测 UITextField 的任何更改。 editingChanged() 函数使用 @ObjCAction 注解,以便与 Objective-C 代码互操作。 addTarget() 函数的 action 参数稍后传递 editingChanged() 函数的名称,以便在响应 UIControlEventEditingChanged 事件时调用它。

UIKitView()update 参数在可观察的 message 状态值更改时调用:

update = { textField -> textField.text = message }

该函数更新 UITextFieldtext 属性,以便用户看到更新后的值。

示例项目 中探索此示例的代码。

下一步

您还可以探索 Compose Multiplatform 与 SwiftUI 框架集成 的方式。

22 四月 2025