I’m building a reference app of different flower types, and each flower type will have its own view (organized by category). To help the user find what they are looking for, I created a search page that will contain an array of all the flower types available in my app. A simplified version of the search page looks like this:
import SwiftUI
struct SampleSearchView: View {
let names = ["carnations", "daisies", "lilacs", "lillies", "roses"]
@State private var searchText = ""
var body: some View {
NavigationView {
List {
ForEach(searchResults, id: \.self) { name in
NavigationLink(destination: Text(name)) {
Text(name)
}
}
}
.searchable(text: $searchText) {
ForEach(searchResults, id: \.self) { result in
Text("\(result)").searchCompletion(result)
}
}
.navigationTitle("Search for Flowers")
}
}
var searchResults: [String] {
if searchText.isEmpty {
return names
} else {
return names.filter { $0.contains(searchText) }
}
}
}
I’m generally happy with the functionality of this search page. However, I want to be able to link the search results to its corresponding view. For example, rather than having the NavigationLink destination for “roses” be just text of the word “roses”, I want the destination be the view file that I created for roses, MainRosesView( ).
I thought it might require me to create a func that uses “if” statements to correlate search results with an associated view, but all attempts I’ve made have been unsuccessful.
Please help steer me in the right direction. I suspect the answer is simpler than it appears.
Thank you in advance!