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

SwiftUI Sheet弹窗中自定义键盘按钮不显示问题求助

SwiftUI弹窗中键盘工具栏按钮不显示的解决办法

问题根源

SwiftUI的键盘工具栏(.toolbar(placement: .keyboard))需要视图处于导航容器(NavigationStack/NavigationView)的环境中才能正常渲染。你弹窗里的EditView没有被导航容器包裹,导致工具栏按钮无法显示;而弹窗外部的视图大概率处于导航环境中,所以代码能正常运行。

解决方案

将EditView的内容包裹在导航容器内即可,根据iOS版本选择对应的容器:

适配iOS 16+(使用NavigationStack)

struct EditView: View {
    @State private var name = ""

    var body: some View {
        NavigationStack {
            TextField("Enter your name", text: $name)
                .textFieldStyle(.roundedBorder)
                .toolbar {
                    ToolbarItemGroup(placement: .keyboard) {
                        Button("insert Tom") {
                            print("Clicked")
                            name.append(" Tom")
                        }
                    }
                }
        }
        // 可选:隐藏导航栏,不影响键盘工具栏
        .navigationBarHidden(true)
    }
}

适配iOS 15及以下(使用NavigationView)

struct EditView: View {
    @State private var name = ""

    var body: some View {
        NavigationView {
            TextField("Enter your name", text: $name)
                .textFieldStyle(.roundedBorder)
                .toolbar {
                    ToolbarItemGroup(placement: .keyboard) {
                        Button("insert Tom") {
                            print("Clicked")
                            name.append(" Tom")
                        }
                    }
                }
        }
        // 可选:隐藏导航栏,不影响键盘工具栏
        .navigationBarHidden(true)
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 21:52:04