swiftui (iOS15) return the touched word in Text

Viewed 38

I want to color a word in a sentence when touched, how can I get it?

var body: some View {
        VStack(alignment: .center) {
            Text("Hello world")
            .gesture(){
             // how to get the touched word?
            }
        }    
    }
1 Answers
 struct ContentView: View {
    
    @State var wordSelected = ""
    
    var body: some View {
        VStack(alignment: .center) {
            
            let myText = "hello world"
            let arrayOfText = myText.components(separatedBy: " ")
            
            HStack {
                ForEach(0..<arrayOfText.count, id: \.self)  { index in
                    Text(arrayOfText[index])
                        .foregroundColor(wordSelected == arrayOfText[index]  ? .red : .black )
                        .onTapGesture {
                            wordSelected = arrayOfText[index] 
                        }
                }
            }
            
            
        }
        
        
    }
    
    
}

when you click on a word the other word is no longer colored

Related