Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

compose-swift-navigation3

English | 한국어

Native UIKit navigation for Compose Multiplatform apps built with Navigation 3. On iOS, the library connects your Kotlin back stacks to real UITabBarController and UINavigationController instances. Android, desktop, and web run your existing NavDisplay and app UI through the otherPlatforms block.

Routes, back stacks, entry providers, screens, ViewModels, and the root App() stay in common code. The library is implemented in Kotlin; it requires no Swift navigation layer.

This README describes the current source version, 1.0.0-alpha02-dev10. The version verified on Maven Central is 1.0.0-alpha01. For the latest APIs below, including badges, menu enabled state, primary actions, and navigation tint, publish the current source to local Maven or use a project dependency.

Table of contents

Features

  • Native push/pop transitions, back buttons, cancellable edge-swipe back, back-button history menus, and tab reselection.
  • Independent tab stacks with retained screen state; shared screens can be pushed above any selected tab.
  • Navigation bar titles, collapsing large titles, image bar buttons, badges and primary actions, menu items with enabled state and badges, bottom toolbars, and UISearchController search.
  • Compose image tab icons, navigation tint, and selected-tab tint.
  • Vertical scrolling backed by UIKit physics, bounce, scroll-to-top, and keyboard insets.
  • Navigation 3 decorators for saveable state and per-entry ViewModels; optional iOS scene restoration.
  • Root switching between NativeStack and NativeTabs, such as sign-in and main flows.
  • System Liquid Glass on iOS 26+ when built with iOS 26 SDK or later, unless the app opts out with UIDesignRequiresCompatibility. Earlier supported iOS versions use their native system appearance.

Kotlin owns the back stack. Native pops call the app's back callback once per removed entry; cancelled gestures leave the Kotlin stack unchanged. A new Kotlin back stack received during a transition takes precedence; the earlier native pop is not applied again to that new stack.

Installation

Run from this repository root to publish the current source to your local Maven repository:

./gradlew :library:publishToMavenLocal

In the consuming app, add mavenLocal() to its dependency repositories before mavenCentral(), keeping google(). Add the library to the shared module:

// settings.gradle.kts
dependencyResolutionManagement {
    repositories {
        google()
        mavenLocal()
        mavenCentral()
    }
}
// shared/build.gradle.kts
kotlin {
    sourceSets {
        commonMain.dependencies {
            implementation("zone.ien.navigation:navigation:1.0.0-alpha02-dev10")
        }
    }
}

Alternatively, include the existing library module in your build and use a project dependency, as the example module does.

To use the Maven Central release, keep google() and mavenCentral(), omit mavenLocal(), and specify version 1.0.0-alpha01. Check the Maven metadata for published versions. That release does not contain every API in the current source.

Automated publishing

The publishing workflow runs when a GitHub Release or prerelease is published. Its tag must match lib-version-name in gradle/libs.versions.toml (for the current source: v1.0.0-alpha02-dev10). After the full CI passes for the same release commit, it signs all library targets, uploads them to Maven Central, and automatically releases them.

Configure the same Actions Secrets as compose-hig: SONATYPE_USERNAME, SONATYPE_PASSWORD (Central Portal token), GPG_KEY (ASCII-armored private key), and GPG_PASSWORD (key passphrase). The Central Portal account must have permission to publish zone.ien.navigation, and the signing public key must be available on a key server. The workflow does not print secret values.

Your app also needs:

  • The Kotlin serialization plugin for @Serializable routes, matching the app's Kotlin version.
  • org.jetbrains.androidx.navigation3:navigation3-ui:1.2.0 for NavDisplay outside iOS.
  • Compose Material 3 if your app uses the Material UI shown below.
  • org.jetbrains.androidx.lifecycle:lifecycle-viewmodel-navigation3:2.11.0 if you need per-entry ViewModels.

The library exposes androidx.navigation3:navigation3-runtime:1.2.1 transitively and does not depend on navigation3-ui or Material 3. See the version catalog and compatibility for the repository's toolchain.

Quick start

After installation, put this minimal stack in commonMain. Imports are included; enable the serialization plugin first. Register NavKey subtypes so non-Android targets can save the back stack.

import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.navigation3.runtime.NavKey
import androidx.navigation3.runtime.entryProvider
import androidx.navigation3.runtime.rememberNavBackStack
import androidx.navigation3.ui.NavDisplay
import androidx.savedstate.serialization.SavedStateConfiguration
import kotlinx.serialization.Serializable
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.modules.subclass
import zone.ien.navigation.NativeNavigationFrame
import zone.ien.navigation.NativeStack
import zone.ien.navigation.NativeScrollContent
import zone.ien.navigation.nativeContentPadding
import zone.ien.navigation.nativeScreen

@Serializable data object Home : NavKey
@Serializable data class Detail(val id: Int) : NavKey

private val navigationConfiguration = SavedStateConfiguration {
    serializersModule = SerializersModule {
        polymorphic(NavKey::class) {
            subclass(Home::class)
            subclass(Detail::class)
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun App() {
    NativeNavigationFrame(frame = { content ->
        MaterialTheme { NativeScrollContent { content() } }
    }) {
        val backStack = rememberNavBackStack(navigationConfiguration, Home)
        val provider = remember(backStack) {
            entryProvider<NavKey> {
                entry<Home>(metadata = nativeScreen(title = "Home")) {
                    Button(
                        onClick = { backStack.add(Detail(1)) },
                        modifier = Modifier.padding(nativeContentPadding()),
                    ) { Text(text = "Open detail") }
                }
                entry<Detail>(metadata = { key -> nativeScreen(title = "Detail ${key.id}") }) { key ->
                    Text(text = "Detail ${key.id}", modifier = Modifier.padding(nativeContentPadding()))
                }
            }
        }
        NativeStack(backStack = backStack, entryProvider = provider) {
            Scaffold(
                topBar = {
                    TopAppBar(
                        title = { Text(text = title.orEmpty()) },
                        navigationIcon = {
                            if (canGoBack) TextButton(onClick = onBack) { Text(text = "Back") }
                        },
                    )
                },
            ) { padding ->
                NavDisplay(entries = entries, modifier = Modifier.padding(padding), onBack = onBack)
            }
        }
    }
}

Android calls setContent { App() }; desktop calls App() inside its window. In iosMain, expose the native root:

import platform.UIKit.UIViewController
import zone.ien.navigation.NativeNavigationViewController

fun MainViewController(): UIViewController = NativeNavigationViewController { App() }

Embed it from SwiftUI as below, with import SwiftUI, import UIKit, and your Kotlin framework import (Shared in the example). Keep the existing UIViewControllerRepresentable if you already have one.

struct ComposeView: UIViewControllerRepresentable {
    func makeUIViewController(context: Context) -> UIViewController {
        MainViewControllerKt.MainViewController()
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}
// ComposeView().ignoresSafeArea()

A UIKit app can assign the result to window.rootViewController. Tap Open detail, then go back. iOS uses the system navigation controller; Android/desktop use the Material bar above. To try the complete repository example, run example/run-sample.sh ios or example/run-sample.sh android from the repository root.

Migrating an existing Navigation 3 app

Keep your routes, navigator, back stacks, entry provider, ViewModels, and screen back handlers. Make these scoped changes:

Existing code Change
NavDisplay(backStack, entryProvider, entryDecorators, ...) Wrap it with NativeStack or NativeTabs; pass the decorated entries and onBack from its receiver to NavDisplay
Material Scaffold, top and bottom bars Keep them in otherPlatforms; render title, bar items, search, and tabs from NativeNavigationScope
Screen titles Declare static titles in nativeScreen; dynamic titles in NativeBarItems
Per-screen TopAppBar and back button Move to the app chrome, or hide existing screen chrome with if (!LocalNativeScreen.current)
Theme, DI, root scaffold, snackbar host Put DI locals in NativeNavigationFrame.providers; theme and screen UI wrappers in frame
Screen innerPadding Use rememberNativeScroll(state) for scrolling screens or nativeContentPadding() otherwise
Outer stack over the tabs Pass its detail entries to NativeTabs(sharedBackStack = ...), excluding the entry that represented the tabs
iOS ComposeUIViewController { App() } Use NativeNavigationViewController { App() }; embed with .ignoresSafeArea()

Check Android behavior after moving the chrome. On iOS, test push, native back, edge swipe and cancellation, large-title scrolling, tab state retention, shared screens, and optional restoration on both iOS 18.x (18.2+) and iOS 26+.

Adding the library to a basic Material 3 app

This walkthrough follows the Home and Settings tabs in App.kt. Complete installation first. If your Material 3 app does not use Navigation 3 yet, add NavKey routes, rememberNavBackStack, and an entryProvider as shown in Quick Start. The library does not inspect Material 3 screens automatically; declare the navigation structure and titles explicitly.

1. Identify the existing Material layout

This fragment is the UI portion of an existing App(). stacks contains the per-tab back stacks, selectedTab is the selection state, and provider is the existing entry provider.

MaterialTheme {
    Scaffold(
        topBar = { TopAppBar(title = { Text(text = "Home") }) },
        bottomBar = {
            NavigationBar {
                listOf("Home", "Settings").forEachIndexed { index, label ->
                    NavigationBarItem(
                        selected = selectedTab == index,
                        onClick = { selectedTab = index },
                        icon = { Text(text = label) },
                    )
                }
            }
        },
    ) { padding ->
        NavDisplay(
            backStack = stacks[selectedTab],
            entryProvider = provider,
            onBack = { stacks[selectedTab].removeLastOrNull() },
            modifier = Modifier.padding(padding),
        )
    }
}

Keep the routes, per-tab back stacks, and navigation calls such as backStack.add(...). The sample's route and serialization declarations are in AppNavigation.kt.

2. Move the existing Scaffold into NativeTabs

Here is the updated App(). See the complete App.kt for imports. It uses the sample's existing HomeScreen, SettingsScreen, DetailScreen, and route declarations.

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun App() {
    val home = rememberNavBackStack(navigationConfiguration, HomeRoute)
    val settings = rememberNavBackStack(navigationConfiguration, SettingsRoute)
    var selectedTab by rememberSaveable { mutableIntStateOf(0) }
    val stacks = listOf(home, settings)
    val openDetail: (Int) -> Unit = { id -> stacks[selectedTab].add(DetailRoute(id)) }

    // Apply the existing app theme and scroll bounce to each iOS screen.
    NativeNavigationFrame(frame = { content ->
        MaterialTheme { NativeScrollContent { content() } }
    }) {
        // Use native tabs and stacks on iOS, and the Material UI below elsewhere.
        NativeTabs(
            tabs = listOf(
                NativeTab("Home", "house", home),
                NativeTab("Settings", "gearshape", settings),
            ),
            selectedTab = selectedTab,
            onTabSelected = { selectedTab = it },
            entryProvider = entryProvider {
                // Declare entry metadata so UIKit knows the title before pushing.
                entry<HomeRoute>(metadata = nativeScreen(title = "Home", largeTitle = true)) {
                    HomeScreen(onOpenDetail = openDetail)
                }
                entry<SettingsRoute>(metadata = nativeScreen(title = "Settings", largeTitle = true)) {
                    SettingsScreen(onOpenDetail = { openDetail(42) })
                }
                entry<DetailRoute>(metadata = { route -> nativeScreen(title = "Detail ${route.id}") }) { route ->
                    DetailScreen(id = route.id)
                }
            },
        ) {
            // Existing Material 3 + NavDisplay layout. This block does not run on iOS.
            Scaffold(
                topBar = {
                    TopAppBar(
                        title = { Text(text = title.orEmpty()) },
                        navigationIcon = {
                            if (canGoBack) TextButton(onClick = onBack) { Text(text = "Back") }
                        },
                    )
                },
                bottomBar = {
                    NavigationBar {
                        tabs.forEachIndexed { index, tab ->
                            NavigationBarItem(
                                selected = selectedTab == index,
                                onClick = { onTabSelected(index) },
                                icon = { Text(text = tab.title) },
                            )
                        }
                    }
                },
            ) { padding ->
                NavDisplay(entries = entries, onBack = onBack, modifier = Modifier.padding(padding))
            }
        }
    }
}
  • Move the existing MaterialTheme or app theme to NativeNavigationFrame.frame. NativeScrollContent applies iOS scroll bounce to the screen content.
  • Pass the existing back stacks and tab selection state to NativeTabs, and add nativeScreen titles to entries. house and gearshape are iOS SF Symbols names; keep rendering Material icons in the existing NavigationBarItem.
  • The trailing block is otherPlatforms. Android, Desktop, and other non-iOS platforms run the existing Scaffold there. Use the block's entries, onBack, title, canGoBack, tabs, and onTabSelected, and pass entries to NavDisplay instead of backStack and entryProvider.
  • iOS uses real UIKit tab and navigation bars instead of running that block. If a screen also has its own TopAppBar, wrap it in if (!LocalNativeScreen.current) to avoid duplicate chrome.
  • For an app without tabs, use NativeStack(backStack, entryProvider = provider) { ... } from Quick Start. If you already use a per-entry ViewModel decorator, move it to entryDecorators on NativeTabs or NativeStack.

3. Connect screen scrolling and padding

Reuse the existing LazyColumn state and connect both returned values. This is the body of HomeScreen(onOpenDetail); Screens.kt contains the complete implementation and imports.

val state = rememberLazyListState()
val scroll = rememberNativeScroll(state)
LazyColumn(
    state = state,
    userScrollEnabled = scroll.userScrollEnabled,
    contentPadding = scroll.contentPadding,
    modifier = Modifier.fillMaxSize(),
) {
    items(50) { id ->
        ListItem(
            headlineContent = { Text(text = "Row $id") },
            modifier = Modifier.clickable { onOpenDetail(id) },
        )
    }
}

For a non-scrolling screen, apply Modifier.padding(nativeContentPadding()). On Android and other non-native platforms this native padding is zero, so keep using the Scaffold padding above. On iOS it supplies native bar and keyboard insets; do not add system-bar insets or imePadding() again. See Scrolling and content insets for details.

4. Change the iOS entry point

Replace the existing ComposeUIViewController { App() } with the following. Android and Desktop entry points continue calling App().

import zone.ien.navigation.NativeNavigationViewController

fun MainViewController() = NativeNavigationViewController { App() }

The existing SwiftUI UIViewControllerRepresentable uses this return value and is embedded with .ignoresSafeArea() (Quick Start bridge). After migration, check the Material bars and back navigation on Android, plus tab switching, detail push, the back button, edge swipe, and scrolling on iOS.

Themes, locals, and state ownership

NativeNavigationFrame(
    providers = { content -> CompositionLocalProvider(LocalAppGraph provides graph, content = content) },
    frame = { content -> AppTheme { RootScaffold { content() } } },
) {
    NativeStack(backStack = backStack, entryProvider = entryProvider) {
        NavDisplay(entries = entries, onBack = onBack)
    }
}

This fragment uses your existing LocalAppGraph, graph, AppTheme, and RootScaffold.

  • Outside iOS, providers { frame { content() } } wraps the app once. On iOS, every entry has its own controller and composition: providers wraps both the UI-free navigation host and each screen; frame wraps each screen.
  • Emit no UI in providers or outside frame/the navigation declaration's otherPlatforms block. The iOS host rejects UI nodes. Move app-level dialogs into screens, or use an implementation backed by a system alert on iOS.
  • The host supplies lifecycle, ViewModel, saved-state owners, LocalUIViewController, and LocalDensity, so shared resource lookups and native alert integrations can work there. UI-dependent themes belong in frame.
  • Read LocalNativeScreen.current inside screen content/frame to hide Compose chrome and apply imePadding() only outside native screens. Do not add system-bar insets again; native content padding already includes them.
  • Native bars follow the system light/dark appearance, not a forced Compose theme. Use a system-following theme to keep them aligned. You may also wrap entry content with an existing NavEntryDecorator instead of NativeNavigationFrame.
  • Entry providers can retain captured ordinary values because entries are recreated on back-stack changes. Read changing values through State, rememberUpdatedState, or a ViewModel.
  • State holders should own the MutableState returned by rememberSaveable directly. Copying to a saved value in SideEffect misses changes when the caller does not recompose.

API

Public APIs live in zone.ien.navigation. The common source and iOS source contain their declarations and KDoc.

API Purpose
NativeStack, NativeTabs, NativeTab Common declarations for a stack, tabs, and each tab's stack
NativeNavigationScope<T> Decorated entries and chrome data passed to otherPlatforms
NativeNavigationFrame, LocalNativeScreen App-wide providers/frame and native-screen detection
nativeScreen, NavEntry.nativeTitle, nativeLargeTitle, nativeHidesTabBar, nativeTitleImage Entry metadata and accessors
rememberNativeScroll, NativeScroll, NativeScrollContent, nativeContentPadding, Modifier.nativeScrollExclusion() Native vertical scroll, content bounce, and insets
NativeNavigationTint, NativeTabBarTint Navigation action and selected-tab tint
NativeBarItems, NativeBarButton, NativeMenuAction, NativeBarContent Bar declarations and data
NativeSearchBar, NativeSearch Search declaration and data
NativeBarState, ProvideNativeBarState Collect declarations around a plain NavDisplay without NativeStack/NativeTabs
NativeNavigationViewController, saveNativeNavigationState iOS navigation host and optional state serialization
ComposeScreenViewController iOS standalone Compose screen for an app-owned UINavigationController

Stacks, tabs, and shared screens

Use observable back stacks (rememberNavBackStack or a snapshot state list). Navigation is ordinary list mutation:

backStack.add(Detail(3))
backStack.removeLastOrNull()
backStack[backStack.lastIndex] = Detail(103)
while (backStack.size > 1) backStack.removeLastOrNull()

These are push, pop, replace, and pop-to-root respectively. For tabs, register every tab/shared route in your provider and serializer configuration, then declare:

val home = rememberNavBackStack(navigationConfiguration, Home)
val settings = rememberNavBackStack(navigationConfiguration, Settings)
val shared = rememberNavBackStack(navigationConfiguration)
var selectedTab by rememberSaveable { mutableIntStateOf(0) }

NativeTabs(
    tabs = listOf(
        NativeTab("Home", systemImage = "house", backStack = home),
        NativeTab("Settings", systemImage = "gearshape", backStack = settings),
    ),
    selectedTab = selectedTab,
    onTabSelected = { selectedTab = it },
    sharedBackStack = shared,
    entryDecorators = listOf(
        rememberSaveableStateHolderNavEntryDecorator(),
        rememberViewModelStoreNavEntryDecorator(),
    ),
    entryProvider = entryProvider,
) { MaterialChrome() }

This fragment extends the quick start with your Settings route, provider, and NativeNavigationScope<NavKey>.MaterialChrome() renderer; the current minimal App.kt puts the Material Scaffold and NavDisplay directly inside the block instead of using a separate renderer.

  • iOS creates a UITabBarController with one UINavigationController per tab. Each tab's decorated entries retain saveable state and ViewModels on other platforms too.
  • sharedBackStack may be empty. Its screens always hide the tab bar and push above the selected tab. onSharedBack removes one shared entry. If the app changes selectedTab while a shared screen is visible, the shared screens move to the new tab without animation.
  • NativeStack and NativeTab default onBack to removing the last entry when the supplied list is mutable. Custom callbacks, including onSharedBack, must pop exactly one entry. Otherwise UIKit and Kotlin diverge, and a subsequent stack change can push the screen again.
  • NativeStack/NativeTabs default to the saveable-state decorator. Add rememberViewModelStoreNavEntryDecorator() when using per-entry ViewModels. Do not redecorate the entries passed to NavDisplay.
  • Declare one root at a time. Switch between NativeTabs and NativeStack with if (signedIn). iOS cross-fades between hierarchies and disposes the old screens; creating decorators inside each branch clears the departing flow's ViewModels and saveable state.
  • Deep links are parsed by your app. Select the tab and replace/extend its Kotlin stack with all destinations; controllers below the top are created when first shown.

Tab icons can also use Compose Painter values: NativeTab(title = "Home", backStack = home, image = homePainter, selectedImage = selectedHomePainter). The host renders both images before the tab appears, fits them within 25×25pt, and uses UIKit template tint. image takes precedence over systemImage; omitting selectedImage uses the default tab image. The existing SF Symbols constructor and trailing onBack lambda remain supported.

Wrap NativeTabs in NativeTabBarTint(color) { ... } to set the selected tab icon and label tint. Color changes update the existing tab bar; Color.Unspecified restores the system tint. Unselected tab colors and bar appearance remain controlled by UIKit.

Native navigation and tab tint

NativeNavigationTint supplies the iOS back-button, bar-action, and toolbar tint; NativeTabBarTint sets the selected tab icon and label tint. This fragment uses your existing appAccent, AppTheme, backStack, and provider.

import zone.ien.navigation.NativeNavigationTint
import zone.ien.navigation.NativeTabBarTint

NativeNavigationFrame(
    providers = { content ->
        NativeNavigationTint(appAccent) {
            NativeTabBarTint(appAccent) { content() }
        }
    },
    frame = { content -> AppTheme { NativeScrollContent { content() } } },
) {
    NativeStack(backStack = backStack, entryProvider = provider) {
        NavDisplay(entries = entries, onBack = onBack)
    }
}

For a tabbed app, replace NativeStack with the existing NativeTabs declaration. Pass a Color; Color.Unspecified restores each host's default tint. These providers do not change UI on other platforms; use the app's theme there. Unselected tab colors and system-bar backgrounds/appearance are not overridden.

Do not place these providers only inside the screen frame. iOS navigation is declared in a UI-free host composition, so put them in providers as above or wrap NativeStack/NativeTabs directly. Rather than reading screen-theme values such as MaterialTheme.colorScheme in the host, pass the app's chosen accent through State or a UI-free color-token provider.

Rendering on Android, desktop, and web

The library draws no UI on these platforms. Read these NativeNavigationScope values in the block and render your existing components:

Value Meaning
entries Selected tab/stack entries followed by shared entries, already decorated
tabEntries, sharedEntries The two lists separately, for an outer NavDisplay above the tabs
onBack, canGoBack Pop the visible stack, and whether another entry is below the top
title, largeTitle, titleImage Dynamic title or metadata fallback, large-title flag, and optional painter lambda
leading, trailing, toolbar, search Collected bar and search declarations
tabs, selectedTab, onTabSelected Tab configuration and selection; no tabs for NativeStack
tabBarVisible Tabs exist, no shared screen is shown, and no pushed tab entry hides the bar

For an outer stack that covers the tab chrome, use listOf(NavEntry<NavKey>(TabsKey) { TabsChrome(tabEntries) }) + sharedEntries as its entries. TabsKey and TabsChrome belong to your app.

The most recently registered, still-composed screen's bar/search declarations win. An outgoing screen's declarations can remain temporarily when the incoming screen declares none. systemImage names are iOS SF Symbols; choose Android icons in your renderer. See App.kt for the minimal integration. Optional menus, toolbars, and search are omitted from the sample.

Screen metadata and title images

entry<Detail>(metadata = { key -> nativeScreen(title = "Detail ${key.id}", hidesTabBar = true) }) { key ->
    DetailScreen(key.id)
}

DetailScreen is your screen composable.

Parameter Default iOS behavior
title null navigationItem.title; set static titles before push starts
largeTitle false A large title that collapses with scrolling; prefer it only on stack roots
hidesTabBar false Uses UITabBarController; screens pushed above it also keep the bar hidden
titleImage null A @Composable () -> Painter rendered as a 28pt-high titleView with its aspect ratio

For a logo, use nativeScreen(title = "Home", titleImage = { painterResource(Res.drawable.logo) }) with your existing Compose resource. Keep title for VoiceOver and the next screen's back button. On iOS the painter runs in the host before push, outside the screen's theme; screen theme colors and dark-mode resources are not applied. Other platforms render titleImage themselves, for example Image(image(), contentDescription = title, modifier = Modifier.height(28.dp)) after checking the lambda is non-null. Title images are an experimental feature in this project.

Scrolling and content padding

Connect the screen's primary vertical container. UIKit owns pan, deceleration, bounce, scroll-to-top, and keyboard insets; Compose follows its offset. Pass both returned values to the container:

val state = rememberLazyListState()
val nativeScroll = rememberNativeScroll(state, background = MaterialTheme.colorScheme.background)
LazyColumn(
    state = state,
    userScrollEnabled = nativeScroll.userScrollEnabled,
    contentPadding = nativeScroll.contentPadding,
) { /* screen rows */ }
val state = rememberScrollState()
val nativeScroll = rememberNativeScroll(state)
Column(
    Modifier.verticalScroll(state, enabled = nativeScroll.userScrollEnabled)
        .padding(nativeScroll.contentPadding),
) { /* screen content */ }
  • The overloads accept LazyListState, LazyGridState, LazyStaggeredGridState, or ScrollState. Use the same userScrollEnabled/contentPadding wiring for vertical grids.
  • On iOS, disable the container's user scrolling with the returned flag. Otherwise Compose captures the drag and the large title may fail to expand again. Containers that cannot disable their own scrolling need to be replaced or configured with a controllable outer container.
  • Outside native screens, the flag is true and padding is zero. Your existing Scaffold still supplies its usual insets.
  • background fills the area exposed by overscroll; omitting it uses iOS systemBackgroundColor.
  • Connect one vertical container per screen. Leave horizontal lists/grids unconnected. Use Modifier.nativeScrollExclusion() on vertical sliders or reorder handles so drags starting there go to Compose.
  • A non-scrolling screen uses Modifier.padding(nativeContentPadding()). Native bar insets are already included; avoid duplicate WindowInsets or native-screen imePadding().
  • Programmatic Compose scrolling, such as animateScrollToItem or bringIntoView, is synchronized back to the native bar.

Content bounce and fixed elements

rememberNativeScroll connects scroll position to the native bars, while NativeScrollContent marks the content that moves when pulled past an edge. With no fixed elements, wrap screen content once in NativeNavigationFrame.frame, as the current sample does.

When a screen's own Scaffold has fixed buttons or bars, wrap only its content slot. FixedActions and ScreenBody below are existing app composables.

Scaffold(bottomBar = { FixedActions() }) { padding ->
    NativeScrollContent(modifier = Modifier.padding(padding)) {
        ScreenBody()
    }
}

With nested NativeScrollContent wrappers, the inner content owns the bounce so the outer frame and fixed buttons do not move with it. The wrapper is not inserted automatically and does not replace the scroll state, userScrollEnabled, or content-inset connections. Outside native iOS screens it behaves as a regular Box.

Bar items, menus, and search

Declare NativeBarItems inside screen content. The following EditorBar takes screen state and callbacks and declares bar buttons, menu items, and a toolbar together. The current minimal App.kt omits bar-item demos; call this function from a screen that needs these actions.

import androidx.compose.runtime.Composable
import zone.ien.navigation.NativeBarButton
import zone.ien.navigation.NativeBarItems
import zone.ien.navigation.NativeMenuAction

@Composable
fun EditorBar(
    unreadCount: Int,
    canSave: Boolean,
    canDelete: Boolean,
    onOpenNotifications: () -> Unit,
    onSave: () -> Unit,
    onDelete: () -> Unit,
) {
    NativeBarItems(
        trailing = listOf(
            NativeBarButton(
                title = "Notifications",
                systemImage = "bell",
                badge = unreadCount,
                onClick = onOpenNotifications,
            ),
            NativeBarButton(
                title = "More",
                systemImage = "ellipsis.circle",
                menu = listOf(
                    NativeMenuAction(
                        title = "Notifications",
                        systemImage = "bell",
                        badge = unreadCount,
                        onClick = onOpenNotifications,
                    ),
                    NativeMenuAction(
                        title = "Delete",
                        systemImage = "trash",
                        destructive = true,
                        enabled = canDelete,
                        onClick = onDelete,
                    ),
                ),
            ),
            NativeBarButton(
                title = "Save",
                systemImage = "checkmark",
                enabled = canSave,
                isPrimary = true,
                onClick = onSave,
            ),
        ),
        toolbar = listOf(
            NativeBarButton("Notifications", systemImage = "bell", onClick = onOpenNotifications),
        ),
    )
}

leading and trailing are ordered left to right and keep the native back button. The example puts Save last so it appears at the right edge. The toolbar appears only while this screen is on top. Override a dynamic title with NativeBarItems(title = ...); declare static titles needed at the start of a push in nativeScreen(title = ...).

Bar buttons: NativeBarButton

Property Default Behavior
title Required Text, or accessibility label when an image is present
systemImage null iOS SF Symbol name
image null Compose Painter; takes precedence over systemImage
enabled true Button enabled state
badge 0 0: hidden, positive: number, negative: dot
isPrimary false UIKit UIBarButtonItemStyleDone emphasis; adds spacing when placed after a regular trailing button
menu Empty list A non-empty list opens a menu instead of invoking onClick
onClick No-op Invoked by an enabled button without a menu

On iOS, a badged bar item contains a system UIButton and a badge view. isPrimary sets the UIKit bar-item style; it does not guarantee the same emphasized background for a button using a badge customView. The example keeps the primary action and badged button separate.

Native items are rebuilt only when their shape changes, including titles, images, enabled state, badges, or menus. Callback-only changes keep the existing items and invoke the latest action.

Menu items: NativeMenuAction

Declare each menu item as NativeMenuAction and the list as NativeBarButton(menu = listOf(...)). On iOS each item becomes a UIAction inside a UIMenu.

Property Default Behavior
title Required Menu-item title
systemImage null iOS SF Symbol name
image null Compose Painter; takes precedence over systemImage
destructive false System styling for destructive actions such as deletion
enabled true When false, displays disabled and prevents callback execution
badge 0 0: hidden, positive: number, negative: •; shown as an iOS menu subtitle, not a badge overlay
onClick Required Invoked when an enabled item is selected

Menus are flat lists; there are no submenu, separator, or selection-state APIs. Disabling the parent button also prevents menu actions from executing.

Button and menu images

For NativeBarButton.image and NativeMenuAction.image, pass painterResource(...) for PNG/vector resources or rememberVectorPainter(...) for an ImageVector. iOS fits the image within 22×22pt, preserves its aspect ratio, and applies native tint to its alpha mask. Existing constructors and trailing click lambdas remain supported.

NativeBarButton(
    title = "Custom action",
    image = painterResource(Res.drawable.my_icon),
) { performAction() }

NativeMenuAction(
    title = "Vector action",
    image = rememberVectorPainter(myImageVector),
) { performAction() }

Use your app's resource, icon, and action for Res.drawable.my_icon, myImageVector, and performAction.

Rendering outside iOS

The library draws no bar UI there. Render buttons from NativeNavigationScope.leading, trailing, and toolbar, plus items in button.menu, using the app's existing design system. Reflect enabled, badge, image, destructive, and isPrimary as appropriate in that renderer. A menu button opens its menu; selecting an item invokes that NativeMenuAction.onClick. SF Symbols are iOS-specific, so the app supplies icons for other platforms.

The current sample's Material TopAppBar renders only the title and back button. Adding NativeBarItems to a screen alone does not add an Android menu. Material 3 apps can connect DropdownMenu and DropdownMenuItem to the existing bar's action slot; other UI systems use their own menu components.

Search

Your app owns the query and filtering:

var query by rememberSaveable { mutableStateOf("") }
NativeSearchBar(query = query, onQueryChange = { query = it }, placeholder = "Search")

iOS uses a UISearchController below the large title, hides it while scrolling down, and supplies clear/cancel controls. Outside iOS, render scope.search yourself. To collect declarations around a plain NavDisplay, remember a NativeBarState and wrap content with ProvideNativeBarState(state) { ... }.

Screen back handlers

Existing NavigationBackHandler, NavigationEventHandler, and legacy BackHandler work inside native screens. Enabled back handlers receive the native button and edge swipe instead of popping; forward-only handlers do not block native back.

NavigationBackHandler(
    state = rememberNavigationEventState(NavigationEventInfo.None),
    isBackEnabled = hasUnsavedChanges,
    onBackCompleted = { showDiscardDialog = true },
)

Use your existing unsaved-state and dialog state. Back-button history menus that pop multiple screens bypass handlers. Handler-owned swipes receive progress/completion/cancellation but have no UIKit transition animation; the screen must render progress itself.

Optional iOS state restoration

The library serializes navigation and entry rememberSaveable state (including scroll positions) to NSData; the app owns storage. Expose these wrappers from iosMain:

fun MainViewController(restoredState: NSData?): UIViewController =
    NativeNavigationViewController(restoredState, stateVersion = 1) { App() }

fun saveNavigationState(controller: UIViewController): NSData? =
    saveNativeNavigationState(controller)

Use platform.Foundation.NSData, platform.UIKit.UIViewController, and the two zone.ien.navigation APIs above. Replace the quick start's no-argument Swift bridge with this scene-storage bridge:

final class NavigationHolder { var controller: UIViewController? }

struct ComposeView: UIViewControllerRepresentable {
    let restoredState: Data?
    let holder: NavigationHolder

    func makeUIViewController(context: Context) -> UIViewController {
        let controller = MainViewControllerKt.MainViewController(restoredState: restoredState)
        holder.controller = controller
        return controller
    }
    func updateUIViewController(_ uiViewController: UIViewController, context: Context) {}
}

struct ContentView: View {
    @SceneStorage("navigationState") private var navigationState: Data?
    @Environment(\.scenePhase) private var scenePhase
    @State private var holder = NavigationHolder()

    var body: some View {
        ComposeView(restoredState: navigationState, holder: holder)
            .ignoresSafeArea()
            .onChange(of: scenePhase) { _, phase in
                // Save on .inactive: iOS records scene state before .background.
                if phase != .active, let controller = holder.controller {
                    navigationState = MainViewControllerKt.saveNavigationState(controller: controller)
                }
            }
    }
}
  • Save when the scene becomes .inactive; saving only at .background is too late for scene-state capture. @SceneStorage restores after system termination, discards state after user force-quit, and keeps each scene separate. UIKit apps can use UIScene.stateRestorationActivity.
  • Increment stateVersion (default 0) when route serialization or the number/order of rememberSaveable/rememberNavBackStack calls changes. Mismatched versions are ignored. A failed initial host restoration retries without saved data, but matching types at the wrong call site and later screen-composition failures are not caught by that safeguard.
  • Unsupported saveable values, such as arbitrary objects or enums without a suitable saver, are omitted and logged; those values restart with defaults. ViewModels and per-screen SavedStateHandle are not serialized.
  • Shared screens use the same restoration mechanism; they always sit over the selected tab.

Compatibility and limitations

These are the repository's configured versions, not a claim that every version combination is supported:

Component Configuration
Kotlin / Compose Multiplatform 2.4.21 / 1.12.2
Navigation 3 runtime / UI 1.2.1 / 1.2.0
Lifecycle / Material 3 (example) 2.11.0 / 1.12.0-alpha03
AGP / Gradle 9.3.1 / 9.7.0
Gradle daemon / compilation JetBrains Runtime 25 / JDK 17 toolchain
Android minSdk 29, compileSdk/targetSdk 37
iOS 18.2+, iosArm64 and iosSimulatorArm64; Liquid Glass requires an iOS 26+ SDK build
Other library targets jvm, browser-only js and wasmJs

CI runs JVM, Android host, iOS simulator, JS, and Wasm tests and builds the Android/desktop examples. It does not build the iOS app or run XCUITest. The repository records XCUITest runs on iOS 18.5 and 27.2 and manual Android checks in AGENTS.md; these are prior results, not a guarantee for every current change. The latest recorded title-image run on iOS 27.2 passed 15 UI tests; iOS 18.x was not rerun for that feature.

Known boundaries:

  • No runtime OS-version branches. iOS 26-only features such as tab-bar minimization, bottomAccessory, explicit glass effects, and search tabs are not exposed.
  • Tabs are root-only. Switch root declarations for login/main flows; nested tabs and a navigation modal API are not supported.
  • iOS never calls otherPlatforms, so its NavDisplay transition settings and sceneStrategy do not apply. All entries are pushed full screens. Present dialogs and bottom sheets within screen content instead of making them navigation entries.
  • Large titles on pushed screens can overlap inline titles during interactive back when the previous large title is collapsed, as in UIKit. Prefer large titles only on stack roots.
  • Equal content keys share Navigation 3 state. Duplicate routes work, but are not independent state instances merely because they were pushed twice.
  • One vertical scroll container per screen; nested vertical containers are not synchronized. Lazy layouts have no native scroll indicator. Containers must allow user scrolling to be disabled.
  • Custom Compose views in native bar buttons, search scopes/tokens, and separate search-results controllers are not supported.
  • Physical devices, iPad, VoiceOver, hardware-keyboard back delivery, Compose text-field focus/keyboard interactions, and scroll performance have not been fully verified. Full-screen gesture overlays and fine landscape safe-area behavior also need further validation.

Example apps

The example shares one App() across Android, desktop, and iOS. It keeps only Home and Settings tabs plus a detail screen. Comments marked 추가: identify the integration added to an ordinary Material 3 Scaffold + Navigation 3 NavDisplay app: native tabs, screen metadata, theme and scroll integration, and the iOS entry point. Optional login, search, menus, title images, and process restoration demos are omitted.

example/run-sample.sh
example/run-sample.sh ios
example/run-sample.sh android
./gradlew :example:desktopApp:run

Run from the repository root. The script builds, installs, and launches the app. Use IOS_SIM_UDID to select an iOS simulator; ANDROID_SERIAL selects an Android device, and ANDROID_AVD selects an emulator to start if needed. The iOS viewer is DeviceHub on Xcode 27; the script opens the available viewer. There is no web example app.

Build and test

Run these commands from the repository root; iOS tasks require macOS and Xcode. The Gradle daemon uses the pinned JetBrains Runtime 25; compilation uses JDK 17, automatically provisioned when absent.

./gradlew jvmTest
./gradlew testAndroidHostTest
./gradlew iosSimulatorArm64Test
./gradlew jsTest wasmJsTest
./gradlew :example:androidApp:assembleDebug :example:desktopApp:jar
xcrun simctl list devices available
xcodebuild -project example/iosApp/iosApp.xcodeproj -scheme example.iosApp \
  -configuration Debug -destination 'platform=iOS Simulator,name=iPhone 17,OS=27.2' \
  -derivedDataPath build/xcode build
example/iosUITests/run.sh <UDID>
python3 -I example/iosUITests/timeline.py build/ui-tests/<UDID>
  • Pick an available simulator name/OS or UDID. Use a separate simulator for UI tests because they terminate/relaunch the app.
  • The example.iosApp scheme currently lives in ignored xcuserdata; a fresh clone may need a scheme created in Xcode before the command above works.
  • The UI harness builds/installs the example and tests it from a separate Xcode project. Results, app logs, and periodic screenshots go to build/ui-tests/<UDID>/.
  • Web tests run in a headless browser, not Node.js. After changing web dependencies, run ./gradlew kotlinUpgradeYarnLock kotlinWasmUpgradeYarnLock.
  • If restoration tests report RESTORE none on a reused simulator, check scene-session logs and retry on a fresh supported simulator; the repository records simulator scene-state failures. Search tests have also shown simulator keyboard-dependent failures; see the verification history.

Project structure

.
├── library/
├── example/
│   ├── shared/
│   ├── androidApp/
│   ├── desktopApp/
│   ├── iosApp/
│   ├── iosUITests/
│   └── run-sample.sh
├── gradle/libs.versions.toml
└── .github/workflows/

library is the publishable KMP module. example/shared owns the common app and the static Shared framework; the other app folders are platform entry points. iosApp and iosUITests are Xcode projects, not Gradle modules. CI is in gradle.yml; publish.yml publishes the library to Maven Central when a GitHub Release is created.

Contributing and references

Read AGENTS.md for project goals, architecture decisions, contributor instructions, and verification history. Keep library code in library and demo/test-only behavior in example.

Related official work:

These are references, not dependencies or an identical architecture: this library uses UIKit from Kotlin/Native, keeps Kotlin back stacks authoritative, and uses native controllers on all supported iOS versions.

License

Apache License 2.0

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages