Is it possible to highlight row on mouse hover in SwiftUI

Viewed 746

I'm trying to make a list with rows that change background colour when mouse passes over. But with the current code all the rows are getting highlighted on hover.

struct ContentView: View {
    @State private var overText = false
    
    var body: some View {
        
        List{
            ForEach(0 ..< 3){ item in
                Row(text: "hhaha")
                        .background(Color(overText ? .systemBlue : .clear))
                        .onHover(perform: { hovering in
                            overText.toggle()
                        })
            }
        }
     
    }
}

Here is the current result

enter image description here

This is what I'm trying to achieve

enter image description here

1 Answers

Yes, because bool toggled for all rows, instead we need to store hovered item, like

struct ContentView: View {
    @State private var overText = -1
    
    var body: some View {
        
        List{
            ForEach(0 ..< 3){ item in
                Row(text: "hhaha")
                        .background(Color(overText == item ? .systemBlue : .clear))
                        .onHover(perform: { hovering in
                            overText = item
                        })
            }
        }
    }
}
Related