SwiftUI 手动控制Text Filed的提交
SwiftUI Manually control the submission of Text Filed
TextField("", text: $searchText, onCommit: { print("Commit") })
Button(action: {
searchText = "test"
// Do Something
}) { Text("Search test") }
如何在按下按钮时提交文本字段
您可以尝试类似的方法,例如:
struct ContentView: View {
@State var searchText = ""
var body: some View {
TextField("", text: $searchText, onCommit: { onMySubmit() })
// ios15
// .onSubmit {
// onMySubmit()
// }
Button(action: {
searchText = "test"
onMySubmit()
}) {
Text("Search test")
}
}
func onMySubmit() {
print("-----> onMySubmit searchText: \(searchText)")
}
}
EDIT1:按下另一个视图上的按钮,问题。
我展示的方法在这种情况下也非常合适。将 onMySubmit
包含在 ObservableObject
中
class,如:
class MyModel: ObservableObject {
@Published var searchText = ""
...
func onMySubmit() {
print("-----> onMySubmit searchText: \(searchText)")
}
}
struct ContentView: View {
@StateObject var myModel = MyModel()
var body: some View {
TextField("", text: $myModel.searchText, onCommit: { myModel.onMySubmit() })
// ios15
// .onSubmit {
// myModel.onMySubmit()
// }
Button(action: {
myModel.searchText = "test"
myModel.onMySubmit()
}) {
Text("Search test")
}
// pass myModel to any other view you want, and
// use it as shown above
}
}
直接或根据需要使用环境传递模型,
并按照我在回答中的描述使用它。如果你不知道如何
要使用 ObservableObject
,有一些关于 SO 的好信息和许多在线教程。
TextField("", text: $searchText, onCommit: { print("Commit") })
Button(action: {
searchText = "test"
// Do Something
}) { Text("Search test") }
如何在按下按钮时提交文本字段
您可以尝试类似的方法,例如:
struct ContentView: View {
@State var searchText = ""
var body: some View {
TextField("", text: $searchText, onCommit: { onMySubmit() })
// ios15
// .onSubmit {
// onMySubmit()
// }
Button(action: {
searchText = "test"
onMySubmit()
}) {
Text("Search test")
}
}
func onMySubmit() {
print("-----> onMySubmit searchText: \(searchText)")
}
}
EDIT1:按下另一个视图上的按钮,问题。
我展示的方法在这种情况下也非常合适。将 onMySubmit
包含在 ObservableObject
中
class,如:
class MyModel: ObservableObject {
@Published var searchText = ""
...
func onMySubmit() {
print("-----> onMySubmit searchText: \(searchText)")
}
}
struct ContentView: View {
@StateObject var myModel = MyModel()
var body: some View {
TextField("", text: $myModel.searchText, onCommit: { myModel.onMySubmit() })
// ios15
// .onSubmit {
// myModel.onMySubmit()
// }
Button(action: {
myModel.searchText = "test"
myModel.onMySubmit()
}) {
Text("Search test")
}
// pass myModel to any other view you want, and
// use it as shown above
}
}
直接或根据需要使用环境传递模型,
并按照我在回答中的描述使用它。如果你不知道如何
要使用 ObservableObject
,有一些关于 SO 的好信息和许多在线教程。