如何将字符串传递给子视图?

时间:2020-02-17 23:04:28

标签: swift swiftui

我想将textBox中的文本传递到子视图并在那里创建一个可滚动的Button。至于输出状态,我们希望'a〜c'垂直排列,并且每个都是一个按钮。

struct ContentView: View {
  var textBox = ["a","b","c"]
  var body: some View {
    VStack {
      ScrollView(.vertical, showsIndicators: false) {
        ForEach(0..<textBox.count) { number in
          ScrollText(text: self.textBox[number].lowercased())
        }
      }
    }
  }
}

struct ScrollText: View {
  @Binding  var text: String
  @State private var flag: Bool = false

  var body: some View {
    Button(action: {
      self.flag.toggle()
    }) {
      Text(text)
    }
  }
}

2 个答案:

答案 0 :(得分:0)

我不清楚问题到底是什么,还是您想要什么,但是我解决了代码中的一些编译器错误,并且按预期显示了三个按钮:

struct ContentView : View {
  var textBox = ["a","b","c"]
  var body: some View {
    VStack {
      ScrollView(.vertical, showsIndicators: false){
        ForEach(textBox, id: \.self) { letter in
          ScrollText(text: letter)
        }
      }
    }
  }
}

struct ScrollText: View {
  var text: String
  @State private var flag: Bool = false

  var body: some View {
    Button(action: {
      self.flag.toggle()
    }, label: {
      Text(text)
    })
  }
}

您的问题是如何传递字符串,因此您不需要@Binding。只需传递一个字符串:)

答案 1 :(得分:0)

如果您要保持ScrollText不变,可以在ContentView中使用它进行修改

struct ContentView: View {
  @State private var textBox = ["a","b","c"] // < make State, so modifiable
  var body: some View {
    VStack {
      ScrollView(.vertical, showsIndicators: false) {
        ForEach(0..<textBox.count) { number in
          ScrollText(text: self.$textBox[number]) // < pass Binding as intended
        }
      }
    }
  }
}