简体   繁体   中英

Multiple Bool with onTapGesture in Combined Text views

We can create combined text views (not line by line) using map and reduce functions.

struct ContentView: View {
@State private var boolArr = [false, false, true, true, false]

   var body: some View {
      (0...boolArr.count).map {
                Text("\($0)")
                }.reduce(Text(""), +)
   }
} 

I want to underline specific text if we tap on the text not all texts. For example, if I tap on text "1", it underlines it. If I tap again, it removes underline. Not all texts underline and remove all underlines, only specific text on which I tap. The following approaches show me Cannot convert value of type 'Int' to expected argument type 'WritableKeyPath<_, _>'

(1...boolArr.count).map {
   Text(" \($0) ").underline(self.$boolArr[$0])
   }.reduce(Text(""), +)
   .onTapGesture(count: 1) {
   self.$boolArr[$0] ? false: true
}

Why $0 is not working? And, which way will be working?

and here is my solution for you. Hope it helps

struct ContentView: View {
    @State private var boolArr = [false, false, true, true, false]

    var body: some View {
        HStack() {
            ForEach([1,2,3,4,5], id: \.self) { number  in
                Text("\(number)")
                    .underline(self.boolArr[number - 1])
                    .onTapGesture(count: 1) {
                        self.boolArr[number - 1].toggle()
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM