Compose Multiplatform UI
Why it matters
- One Compose UI in
commonMaincan replace two native UI codebases, reducing duplicated screens for teams shipping Android and iOS. - Interviewers at KMP shops ask how you structure source sets, where platform-specific code lives, and how Swift consumes the exported framework.
- Compose Multiplatform draws its own UI on iOS with Skia, so fonts, text layout, scrolling feel, and accessibility can behave differently from Android and from native UIKit.
- Knowing the Gradle plugins, the
ComposeUIViewControllerentry point, and the Swift interop rules is the baseline for any KMP UI role.
The simple explanation
- You write one recipe (the composable) in a shared kitchen (
commonMain). - The Android chef (
androidMain) plates it using the Android framework's own graphics stack. - The iOS chef (
iosMain) plates it with a portable kit it brings along (Skia via Skiko). - The recipe is identical; only the plating differs, so the dish can look slightly different.
- A waiter (Swift) picks up the iOS plate through a window (the generated Objective-C header).
- If the recipe needs a tool only the Android chef has (
Context,SharedPreferences), the iOS chef cannot cook it.
What is Compose Multiplatform? It is JetBrains' framework for sharing Jetpack Compose UI code across Android, iOS, desktop, and web, and it is stable for iOS. You write the same @Composable functions with the same androidx.compose.* packages you already use on Android. On Android it uses Google's Jetpack Compose artifacts directly. On iOS it draws the UI itself with Skia through Skiko (Kotlin bindings for Skia) into a Metal-backed view, instead of using UIKit controls. That self-drawing approach explains many iOS-only visual differences.
The Gradle setup uses three plugins: kotlin("multiplatform"), org.jetbrains.compose (Compose Multiplatform), and org.jetbrains.kotlin.plugin.compose (the Compose compiler, required since Kotlin 2.0). Recent Compose Multiplatform versions deprecate the compose.runtime / compose.material3 dependency aliases, so new projects declare the Maven coordinates through the version catalog.
Source sets follow the default hierarchy template:
| Source set | Platform | Typical content |
|---|---|---|
commonMain | All | Shared @Composable functions, state holders, view models |
androidMain | Android | setContent in a ComponentActivity, Android-only APIs |
iosMain | iOS | ComposeUIViewController, UIKit interop |
iosArm64Main | iOS device | Rare device-only tweaks |
iosSimulatorArm64Main | iOS simulator | Rare simulator-only tweaks |
Swift consumes the shared module through a framework binary (binaries.framework { baseName = "Shared" }). Kotlin/Native generates an Objective-C header; Swift imports the framework and calls a top-level Kotlin function that returns the UIViewController built by ComposeUIViewController. Kotlin suspend functions appear in Swift as completion-handler methods that Swift can call with async, but Flow has no direct Swift equivalent, so teams add SKIE or KMP-NativeCoroutines. For platform-specific services, prefer an interface in commonMain plus DI (for example Koin, since Hilt is Android-only) over expect/actual classes, which are still Beta.
Notes
- Compose Multiplatform uses the same
androidx.compose.*packages as Jetpack Compose; the Gradle plugin isorg.jetbrains.compose, but your import paths do not change. - On iOS, Compose renders with Skia (Skiko) into a Metal layer rather than UIKit views. Default fonts and text metrics differ, so do not assume a
Textthat fits on Android fits on iOS; setmaxLinesandoverflowwhere truncation matters. - The iOS entry point is
ComposeUIViewControllerfromandroidx.compose.ui.window. Wrap it in aUIViewControllerRepresentableto show it in SwiftUI. - Declare
iosArm64()for devices andiosSimulatorArm64()for simulators on Apple Silicon Macs.iosX64()is only needed for Intel Mac simulators and is being phased out by Kotlin. - Apply the Compose compiler plugin
org.jetbrains.kotlin.plugin.composealongsideorg.jetbrains.compose; its version matches your Kotlin version. suspendfunctions export to Swift as completion handlers usable withasync;Flowneeds SKIE or KMP-NativeCoroutines to become anAsyncSequence.expect/actualclasses are still Beta. For most platform differences, define an interface incommonMainand provide the implementation from each platform's DI module.- Shared screens can use the multiplatform
ViewModelfrom the JetBrains lifecycle artifacts and Compose Multiplatform resources (Res.string,Res.font) for strings, images, and fonts. binaries.frameworkproduces a static or dynamic.framework(isStatic) that Xcode links. The generated header is Objective-C, so naming and nullability follow Objective-C rules.- SKIE is a Gradle plugin from Touchlab; KMP-NativeCoroutines is a Gradle plugin plus annotations and a Swift package. Neither ships with Compose Multiplatform.
Code example
This shows a shared CounterScreen composable in commonMain with a platform-agnostic state holder, plus the iOS and Android entry points that place it in each platform's view hierarchy.
// --- commonMain: shared Compose UI, zero platform imports ---
package com.example.shared.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.text.style.TextOverflow
// Platform-agnostic state; no Context, no UIViewController
class CounterState {
var count by mutableIntStateOf(0)
private set
fun increment() { count++ }
fun reset() { count = 0 }
}
@Composable
fun CounterScreen() {
val state = remember { CounterState() }
Column {
Text("Count: ${state.count}", maxLines = 1, overflow = TextOverflow.Ellipsis)
Button(onClick = state::increment) { Text("Tap") }
Button(onClick = state::reset) { Text("Reset") }
}
}
// --- iosMain: entry point Swift calls through the generated header ---
// import androidx.compose.ui.window.ComposeUIViewController
// fun MainViewController() = ComposeUIViewController { CounterScreen() }
// --- androidMain: Android entry point ---
// class MainActivity : ComponentActivity() {
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// setContent { CounterScreen() }
// }
// }CounterStatelives incommonMainwith no Android or iOS types, so both platforms compile it unchanged.remember { CounterState() }keeps the state across recompositions, exactly as in Jetpack Compose. For state that must survive configuration changes, use a multiplatformViewModel.ComposeUIViewControllerplays the role ofsetContenton iOS. Swift calls it through the generated header, for exampleMainViewControllerKt.MainViewController()if the file isMainViewController.kt.maxLinesandoverflowmake truncation explicit, so a label that is wider on iOS ends in an ellipsis instead of wrapping and pushing other content down.
Run the idea in plain Kotlin
// One shared state, two platform renderers:
// the shape of a Compose Multiplatform app
interface PlatformRenderer {
fun render(title: String, items: List<String>)
}
class AndroidRenderer : PlatformRenderer {
override fun render(title: String, items: List<String>) {
println("[Android] " + title + " -> " + items.joinToString(", "))
}
}
class IosRenderer : PlatformRenderer {
override fun render(title: String, items: List<String>) {
println("[iOS] " + title + " -> " + items.joinToString(", "))
}
}
class SharedUiState {
var title: String = "Home"
private set
var items: List<String> = listOf("A", "B", "C")
private set
fun addItem(item: String) {
items = items + item
}
fun render(renderer: PlatformRenderer) {
renderer.render(title, items)
}
}
fun main() {
val state = SharedUiState()
val renderers = listOf(AndroidRenderer(), IosRenderer())
println("=== Initial state ===")
renderers.forEach { state.render(it) }
state.addItem("D")
state.addItem("E")
println("=== After adding D and E ===")
renderers.forEach { state.render(it) }
}Expected output:
=== Initial state ===
[Android] Home -> A, B, C
[iOS] Home -> A, B, C
=== After adding D and E ===
[Android] Home -> A, B, C, D, E
[iOS] Home -> A, B, C, D, E
In production
- In a shared product list, long titles wrapped to two lines on iOS and pushed the price below the visible card area. Android looked correct.
- The shared
Texthad nomaxLines, and the app relied on each platform's default font. The iOS default font has different metrics, so the same string was wider on iOS. - The team only reviewed screenshots from Android, so the difference shipped.
- Bundled the brand font with Compose Multiplatform resources and applied it through the shared
MaterialThemetypography, so both platforms measure the same glyphs. - Added
maxLines = 1andoverflow = TextOverflow.Ellipsisto the titleText. - Added screenshot review of the iOS simulator to the release checklist for shared screens.
- The shared view model exposed
StateFlowto Swift. Without a bridge, the iOS team wrote a hand-madeFlowCollectoradapter and started collection when a screen appeared. - Collection was never cancelled when the screen closed, so old screens kept receiving updates and holding memory.
Flowexports to Objective-C as a plain interface, so Swift had noAsyncSequenceand no structured cancellation.
- Applied the SKIE Gradle plugin to the shared module, so Swift sees the
Flowas anAsyncSequenceandsuspendfunctions asasyncfunctions with cancellation support. - Collected the flow in SwiftUI's
.taskmodifier, which cancels automatically when the view disappears. - Removed the hand-written adapter and added a CI job that builds the Swift app against the framework.
Common mistakes
- Importing android.content.Context or SharedPreferences in commonMain. The code will not compile for iOS. Define an interface in
commonMainand provide the Android implementation fromandroidMainthrough DI. - Forgetting iosSimulatorArm64(). Simulators on Apple Silicon Macs need the
iosSimulatorArm64target;iosArm64only covers physical devices. Declare both. - Using expect/actual classes for a platform-specific repository.
expect/actualclasses are still Beta. Use an interface plus DI, which is also easier to fake in tests. - Exposing Flow to Swift without a bridge. Swift sees a plain Objective-C interface, not an
AsyncSequence, so hand-written collectors leak or never cancel. Add SKIE or KMP-NativeCoroutines. - Using Hilt or Dagger in commonMain. Hilt is Android-only and Dagger is JVM-only. Use a multiplatform option such as Koin, or manual constructor injection.
- Assuming text renders identically on Android and iOS. Default fonts and text metrics differ. Ship the same font through Compose resources, set
maxLinesandoverflowwhere it matters, and check iOS screenshots.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“How does Compose Multiplatform render UI on iOS compared to Android?”
“How do you structure a KMP module that uses Compose Multiplatform?”
“What are the main limitations of sharing UI with Compose Multiplatform?”
“How do you bridge Kotlin coroutines and Flow to Swift in a KMP project?”
Quiz
How does Compose Multiplatform draw UI on iOS?
Which dependency injection option works in KMP common code?
What is the iOS entry point for a Compose Multiplatform screen?
How does a Kotlin suspend function appear to Swift through the default Objective-C export?
0 of 4 answered
Mini task
15-minute exercise: wire a shared Compose screen to iOS
-
Open your KMP project. In the shared module's
build.gradle.kts, confirm theorg.jetbrains.composeandorg.jetbrains.kotlin.plugin.composeplugins are applied and Compose runtime, foundation, and material3 are incommonMaindependencies. -
In
commonMain, create aGreetingScreencomposable that takes aname: Stringparameter and renders aTextand aButtonthat increments a rememberedmutableIntStateOfcounter. No Android or iOS imports. -
In
iosMain, addfun GreetingViewController() = ComposeUIViewController { GreetingScreen(name = "iOS") }. -
In
androidMain, add aComponentActivitysubclass that callssetContent { GreetingScreen(name = "Android") }. -
Build the iOS framework with
./gradlew :shared:linkDebugFrameworkIosSimulatorArm64and open the generated header undershared/build/bin/iosSimulatorArm64/debugFramework/. ConfirmGreetingViewControllerappears, then show it in SwiftUI through aUIViewControllerRepresentable.
Done condition: the iOS simulator app shows the greeting and the button increments the counter. The Android app shows the same screen. No platform-specific imports appear in commonMain.