将emptyText发送到Service SwiftUI
如果按钮值将emptyText发送到Service SwiftUI,swiftui,uitextfield,combine,Swiftui,Uitextfield,Combine,如果按钮值.isCancel为true,我想将搜索文本中的空文本发送到AuthorService()。这样我的作者搜索结果将被清除 import SwiftUI import Combine struct AuthorSearchBar: View { @StateObject var service = AuthorService() @Binding var isCancel: Bool @State var emptyText = &quo
.isCancel
为true,我想将搜索文本中的空文本发送到AuthorService()
。这样我的作者搜索结果将被清除
import SwiftUI
import Combine
struct AuthorSearchBar: View {
@StateObject var service = AuthorService()
@Binding var isCancel: Bool
@State var emptyText = ""
var body: some View {
VStack(spacing: 0) {
HStack {
Image(systemName: "magnifyingglass")
if isCancel == false{
TextField("Search", text: $service.searchText)
} else if isCancel {
TextField("Search", text: $service.searchText = "")
//Cannot assign to property: '$service' is immutable
//Cannot assign value of type 'String' to type 'Binding<String>'
//Cannot convert value of type '()' to expected argument type 'Binding<String>'
}
.padding()
.onReceive(Just( self.isCancel ? emptyText : service.searchText), perform: { _ in
service.fetchData()
})
}
}
}
好的,我仍然不确定我是否理解流程,但是让我们试试
有一些假设(在评论中提到),方法可能如下(原始代码是不可测试的,所以答案就在这里准备好了-可能是拼写错误,调整由您决定,但想法应该是明确的):
备选:对获取数据不做任何更改,但在这种情况下,不可能将输入的空字符串与取消的空字符串分开(尽管不清楚这是否重要)
HStack{
图像(系统名称:“放大镜”)
TextField(“搜索”,text:$service.searchText)
.padding()
}
.onReceive(Just(service.searchText)){text in
service.fetchData()文件
}
.onReceive(Just(self.isCancel)){在中取消
如果取消{
service.searchText=“”//描述和代码都不清楚。请详细说明一下好吗?编辑了我的问题我在许多其他地方使用fetchData服务函数。大多数地方我甚至都没有查找文本。那么有没有更好的方法将文本推送到fetchData函数内?请参阅使用其他方法更新…实际上是从两个方面应该明确总的方向。
class AuthorService: ObservableObject {
@Published var searchText : String = ""
func fetchData() {
let parameters = ["index": "authors", "query": "\(searchText)" ]
struct AuthorSearchBar: View {
@StateObject var service = AuthorService()
@Binding var isCancel: Bool
var body: some View {
VStack(spacing: 0) {
HStack {
Image(systemName: "magnifyingglass")
TextField("Search", text: $service.searchText)
.padding()
}
.onReceive(Just(service.searchText)) { text in
if !text.isEmpty { // assuming search only for existed text
service.fetchData(for: text)
}
}
.onReceive(Just(self.isCancel)) { canceled in
if canceled {
// assuming needed to send on explicit cancel
service.fetchData(for: "")
}
}
}
}
}
// pass what should be sent via argument instead of use property
func fetchData(for text: String) {
let parameters = ["index": "authors", "query": "\(text)" ]
...
}
HStack {
Image(systemName: "magnifyingglass")
TextField("Search", text: $service.searchText)
.padding()
}
.onReceive(Just(service.searchText)) { text in
service.fetchData()
}
.onReceive(Just(self.isCancel)) { canceled in
if canceled {
service.searchText = "" // << this activates above onReceive
}
}