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

SwiftUI中如何从Toolbar内收起键盘?

问题:Toolbar内TextField的onSubmit无法收起键盘,反而切换到其他输入框

在SwiftUI中给页面TextField添加键盘工具栏,工具栏内放置另一个TextField后,在工具栏TextField的onSubmit回调中设置focusedField = nil,预期是收起键盘,但实际焦点会切换到页面上的第一个TextField,同时控制台输出错误日志:

-[RTIInputSystemClient remoteTextInputSessionWithID:performInputOperation:]  perform input operation requires a valid sessionID. inputModality = Keyboard, inputOperation = <null selector>, customInfoType = UIEmojiSearchOperations

复现代码:

struct ContentView: View {
    enum FocusedField {
        case type1
        case type2
    }

    @State private var text: String = ""
    @FocusState private var focusedField: FocusedField?

    var body: some View {
        TextField("Type 1", text: $text)
            .focused($focusedField, equals: .type1)
            .toolbar {
                ToolbarItem(placement: .keyboard) {
                    TextField("Type 2", text: $text)
                        .focused($focusedField, equals: .type2)
                        .onSubmit {
                            focusedField = nil // 此代码未收起键盘,反而切换到type1输入框
                        }
                }
            }
    }
}

解决方案

问题根源是:当工具栏内的TextField失去焦点时,系统会自动尝试聚焦页面上其他可交互的输入框,导致仅设置focusedField = nil无法直接收起键盘。可以通过强制让应用内第一响应者 resign 来解决:

修改onSubmit回调代码,直接调用系统方法收起键盘,同时清空焦点状态:

.onSubmit {
    // 强制收起键盘
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
    focusedField = nil
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 15:33:11