How to change each text with onHover

I am new to Swift programming. I am trying to change the content of each text and the colours with onHover as follows.

@State var isHover = false
@State var text = "OUT"
...
let textlist = [text, text]
VStack {
    ForEach(0 ..< textlist.count,  id: \.self){ index in
       Text(textlist[index])
       .foregroundColor(self.isHover ? Color.yellow : Color.white)
       .onHover(perform: { flag in
         self.isHover = flag
         if flag {
           self.text = "IN"
         }else{
           self.text = "OUT"
       }
     })
    }
}

The result was that the contents of both were changed to "IN" from "OUT" and the colours yellow on a mouse over. I just want to change each which a mouse is over. How can I fix this problem? Thank you.

Answered by Claude31 in 746142022

Thanks for the feedback. Don't forget to close the thjread to mark the correct answer. Good continuation.

The state (isHover) is the same for both Text.

You need to make it dependant on the Text.

Here is how:

struct ContentView: View {
    @State var isHover = [false, false]  // Must be an array to store for each Text
    // NOT needed @State var text = "OUT"

    @State var textlist = ["OUT", "OUT"]  // Make it a State var

    var body: some View {
        VStack {
            ForEach(0 ..< textlist.count,  id: \.self){ index in
               Text(textlist[index])
                    .frame(width: 80, height: 40)
               .foregroundColor(self.isHover[index] ? .yellow : .white)  // Color change only for the hovered field
               .onHover(perform: { flag in
                 self.isHover[index] = flag
                 if flag {
                     textlist[index] = "IN"   //  change the textList
                 } else {
                   textlist[index] = "OUT"
               }
             })
            }
        }
        .frame(width: 200, height: 200)
   }
}

Thank you for answering my question. I tried it and I got the result I wanted. I really thank you.

Accepted Answer

Thanks for the feedback. Don't forget to close the thjread to mark the correct answer. Good continuation.

How to change each text with onHover
 
 
Q