我正在嘗試通過搜索欄對資料模型進行搜索。
我的資料模型是以下結構:
struct NoteItem: Codable, Hashable, Identifiable {
let id: UUID
var text: String
var date = Date()
var dateText: String {
let df = DateFormatter()
df.dateFormat = "EEEE, MMM d yyyy, h:mm a"
return df.string(from: date)
}
var tags: [String] = []
var filename: String = ""
var changed: Bool = false
}
應用程式對資料模型上的每個元素進行迭代并填充一個串列,其中 aNavigationLink有兩個Text:一個是 a 的第一行TextEditor,另一個是datamodel.dateText. 串列中的每一項都指向另一個視圖,其中TextEditor顯示完整的datamodel.text
我嘗試添加的搜索僅在datamodel.text. 代碼如下:
struct AllNotes: View {
@EnvironmentObject private var data: DataModel
...
var body: some View {
NavigationView {
List(data.notes) { note in
NavigationLink(
destination: NoteView(note: note, text: note.text),
tag: note.id,
selection: $selectedNoteId
) {
VStack(alignment: .leading) {
Text(getTitle(noteText: note.text)).font(.body).fontWeight(.bold)
Text(note.dateText).font(.body).fontWeight(.light)
}
.padding(.vertical, 10)
}
}
.listStyle(InsetListStyle())
.frame(minWidth: 250, maxWidth: .infinity)
}
.toolbar {
ToolbarItem(placement: .automatic) {
TextField("Search...", text: $searchText)
.textFieldStyle(RoundedBorderTextFieldStyle())
.frame(minWidth: 200)
}
}
}
}
搜索欄是工具列中的一個 TextField。
在 iOS 中,過去,我做過類似的事情:
List(ListItems.filter({ searchText.isEmpty ? true : $0.name.contains(searchText) })) { item in
Text(item.name)
}
但是鑒于搜索欄是工具列中的一個專案,并且我需要使用資料模型中所有文本的搜索來過濾/重新填充串列,而不僅僅是串列,我什至如何開始呢?如何過濾它?我需要填充一個新陣列嗎?如何訪問搜索欄上的文本?是$searchText在我發布的代碼中嗎?我表演data.filter嗎?
我已經沒有想法可以嘗試了。
謝謝你。
編輯:
我有這種作業,但請注意。它弄亂了NavigationLink顯示的方式,它在文本之前添加了隨機的空格。
代碼:
var body: some View {
NavigationView {
List {
ForEach(data.notes.filter { $0.text.contains(searchText) || searchText.isEmpty }) { note in
NavigationLink(
destination: NoteView(note: note, text: note.text),
tag: note.id,
selection: $selectedNoteId
) {
VStack(alignment: .leading) {
Text(getTitle(noteText: note.text)).font(.body).fontWeight(.bold)
Text(note.dateText).font(.body).fontWeight(.light)
}
.padding(.vertical, 10)
}
}
.listStyle(InsetListStyle())
.frame(minWidth: 250, maxWidth: .infinity)
.alert(isPresented: $showAlert, content: {
alert
})
Text("Create a new note...")
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
uj5u.com熱心網友回復:
這是編輯的答案,因此人們不會抱怨:
var body: some View {
NavigationView {
List(data.notes.filter { searchText.isEmpty ? true : $0.text.localizedCaseInsensitiveContains(searchText) }) { note in
NavigationLink(
destination: NoteView(note: note, text: note.text),
tag: note.id,
selection: $selectedNoteId
) {
VStack(alignment: .leading) {
Text(getTitle(noteText: note.text)).font(.body).fontWeight(.bold)
Text(note.dateText).font(.body).fontWeight(.light)
}
.padding(.vertical, 10)
}
}
.listStyle(InsetListStyle())
.frame(minWidth: 250, maxWidth: .infinity)
.alert(isPresented: $showAlert, content: {
alert
})
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/314063.html
