简体   繁体   English

在组合文本视图中使用 onTapGesture 的多个 Bool

[英]Multiple Bool with onTapGesture in Combined Text views

We can create combined text views (not line by line) using map and reduce functions.我们可以使用 map 和 reduce 函数创建组合文本视图(不是逐行)。

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.例如,如果我点击文本“1”,它会在其下划线。 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<_, _>'以下方法向我展示了无法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?为什么 $0 不起作用? 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()
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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