You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI键盘工具栏在UIKit SplitViewController中不显示问题求助

问题解决方案

这个问题的核心是SwiftUI的键盘工具栏依赖导航环境才能正确初始化,直接嵌入UIKit SplitViewController详情视图时缺少该环境,导致首次弹出键盘时工具栏不加载,后台恢复时环境重新计算才显示。

解决方案1:给SwiftUI视图添加导航容器(推荐)

给你的TestContentView包裹NavigationStack(iOS 16+)或NavigationView(iOS 13-15),并可按需隐藏导航栏:

struct TestContentView: View {
    @State private var name = "Test"
    var body: some View {
        NavigationStack {
            TextField("Enter your name", text: $name)
                .textFieldStyle(.roundedBorder)
                .toolbar {
                    ToolbarItemGroup(placement: .keyboard) {
                        Button("Click me!") {
                            print("Clicked")
                        }
                    }
                }
        }
        .navigationBarHidden(true) // 隐藏默认导航栏,不影响键盘工具栏
    }
}

解决方案2:在UIKit侧嵌入导航控制器

如果不想修改SwiftUI代码,可以在UIKit中把UIHostingController嵌入到UINavigationController后,再作为SplitViewController的详情视图:

// 示例UIKit代码
let swiftUIView = TestContentView()
let hostingController = UIHostingController(rootView: swiftUIView)
let navController = UINavigationController(rootViewController: hostingController)
splitViewController?.showDetailViewController(navController, sender: nil)

这样就能确保SwiftUI视图获得正确的导航环境,键盘工具栏会在首次点击TextField时正常显示。

内容的提问来源于stack exchange,提问作者user2793959

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:47:22