在我的应用程序中,我有一个文本框
TextField("", text: $messageText, axis: .vertical)
.submitLabel(.search)
.onSubmit{print("submitted")}
我希望返回键说出它与 .submitLabel 一起执行的“搜索”,并且我希望它将输入的文本($messageText)提交到我的 api(采取行动)并在按下搜索按钮时关闭,而不是简单地在文本字段中添加另一行。
通过打印“已提交”进行测试表明控制台中没有采取任何行动。
我在 UI 上有一个按钮可以执行此操作:
Button {
sendMessage()
messageText = ""
isTyping.toggle()
isResponding.toggle()
}
我想要返回按钮,现在标记为“搜索”以执行按钮正在执行的操作。我正在尝试使用 onSubmit 但它没有被调用,它在文本字段中输入了另一行。我创建了新视图并尝试了 at textfield 和 onsbumit 的简单实现,但我仍然只在文本字段中添加了一行,而没有提交操作。
如何获取键盘上的返回/搜索键以使文本字段执行操作?我正在使用 Xcode 14.2.
这里是完整的代码视图块。
@ViewBuilder
func typingView() -> some View {
VStack {
HStack {
TextField("", text: $messageText, axis: .vertical)
.submitLabel(.search)
.onSubmit{ print("submitted")}
.padding()
.keyboardType(.webSearch)
.ignoresSafeArea(.keyboard)
.font(.system(size: 26, weight: .semibold))
.focused($typingInFocus)
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.75) {
self.typingInFocus = true
}
}
Button {
sendMessage()
messageText = ""
print("sent type")
isTyping.toggle()
print(isTyping)
isResponding.toggle()
}
label: {
Image(systemName: messageText == "" ? "circle" : "arrow.up.circle.fill")
.resizable()
.scaledToFit()
.frame(width: 25, height: 25)
.scaleEffect(messageText == "" ? 1.0 : 1.3)
.foregroundColor(messageText == "" ? .white.opacity(0.0) : .white)
.padding()
}
.disabled(messageText == "")
}
}
}