If you are an iOS user and have ever tried to search for a feature in the settings by typing the name in the search bar, you might have noticed that when you jump to the page with the found feature, the row with the feature is highlighted for a few seconds. In this post, I’ll show a possible implementation for that.
First we create a page with a simple navigation link to jump to the page that contains the feature (in our case VPN).
struct ContentView: View {
var body: some View {
NavigationStack {
NavigationLink("Settings", destination: ListWithHighlightView(search: "VPN"))
}
}
}Then define the Option struct with a simple id, name, and highlight flag (set to true when the option needs to be highlighted).
struct Option: Identifiable {
var id = UUID()
var hi = false
var name = ""
}In the View we create a simple array with some options, show the list of options. When the list is displayed (the onAppear), simply check the name of the item to higlight, if it found, we higlight, than calling in the task a timer for one second, we remove the highligting.
struct ListWithHighlightView: View {
@State var options = [Option(name: "Wi-fi"), Option( name:"VPN"), Option(name: "Sound")]
@State var search = ""
var body: some View {
VStack {
List {
ForEach(0..<options.count) { index in
Text(options[index].name)
.listRowBackground(Color(options[index].hi ? UIColor.systemFill : UIColor.systemBackground))
.onAppear {
if search == options[index].name {
options[index].hi = true
Task {
try await Task.sleep(nanoseconds: 1_000_000_000)
options[index].hi = false
}
}
}
}
}
}
}
}listRowBackground defines the background of the row, which in this case contains only text.
That’s all.