Xcode 14.2中如何让TextField的搜索键触发指定操作?
解决SwiftUI多行TextField搜索键不触发onSubmit的问题
在Xcode14.2中,你遇到的核心问题是垂直方向(多行)的TextField默认会将键盘的回车/搜索键视为换行输入,因此不会触发onSubmit回调。要让搜索键执行指定操作,可通过以下两种方法解决:
方法一:使用submitTriggers(iOS15.4+适用)
给TextField添加.submitTriggers(.textEntry)修饰符,强制让键盘的submit按钮触发onSubmit而非插入换行。直接把按钮的逻辑复用进onSubmit,并手动收起键盘:
TextField("", text: $messageText, axis: .vertical) .submitLabel(.search) .submitTriggers(.textEntry) // 关键:指定触发submit的条件 .onSubmit { // 执行和按钮完全相同的操作 sendMessage() messageText = "" isTyping.toggle() isResponding.toggle() typingInFocus = false // 收起键盘 } .padding() .keyboardType(.webSearch) .ignoresSafeArea(.keyboard) .font(.system(size: 26, weight: .semibold)) .focused($typingInFocus) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) { self.typingInFocus = true } }
方法二:监听文本变化捕获回车(兼容更早iOS版本)
如果需要支持iOS15.4以下版本,可以通过监听文本变化,检测到换行符时执行操作并移除换行:
TextField("", text: $messageText, axis: .vertical) .submitLabel(.search) .onChange(of: messageText) { newValue in guard newValue.hasSuffix("\n") else { return } // 先移除输入的换行符 messageText = String(newValue.dropLast()) // 执行按钮操作 sendMessage() messageText = "" isTyping.toggle() isResponding.toggle() typingInFocus = false // 收起键盘 } .padding() .keyboardType(.webSearch) .ignoresSafeArea(.keyboard) .font(.system(size: 26, weight: .semibold)) .focused($typingInFocus) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) { self.typingInFocus = true } }
注意事项
- 两种方法都需要手动设置
typingInFocus = false来收起键盘,因为执行操作后TextField仍会保持焦点状态。 - 方法一中的
submitTriggers是iOS15.4引入的API,Xcode14.2对应的iOS版本支持该特性,可放心使用。
内容的提问来源于stack exchange,提问作者jacobt
相关产品推荐
相关产品推荐

