I have the following lines of code to show multiple instances of View (MyTextView)
import SwiftUI
struct ContentView: View {
@State var myTextViews = [MyTextView]()
var body: some View {
VStack {
Button {
} label: {
Text("Show me your current text strings")
}.padding(.vertical, 10.0)
VStack {
ForEach(0 ..< myTextViews.count, id: \.self) { _ in
MyTextView()
}
}
Button {
myTextViews.append(MyTextView())
} label: {
Text("Add me!")
}.padding(.vertical, 10.0)
}
}
}
struct MyTextView: View {
@State var text = ""
var body: some View {
ZStack {
TextField("Enter some text", text: $text)
}.padding(.horizontal, 50.0)
}
}
According to the screenshot, I have three instances, each of which contains TextField. After I tap the top button (Show me your current...), I want to show the result from each TextField. How can I do that? Thanks.
I've figured it out accidentally.
import SwiftUI
struct ContentView: View {
@ObservedObject var monster: Monster
var body: some View {
VStack {
Button {
print(monster.items)
} label: {
Text("Show me your current text strings")
}.padding(.vertical, 10.0)
ForEach($monster.items) { item in
MyTextView(id: item.id, text: item.text).environmentObject(monster)
}.padding(.horizontal, 200.0)
Button {
monster.items.append(Keyword())
} label: {
Text("Add me!")
}.padding(.vertical, 10.0)
}
}
}
class Monster: ObservableObject {
@Published var items = [Keyword]()
}
struct Keyword: Identifiable {
var id = UUID()
var text = String()
}
struct MyTextView: View {
@Binding var id: UUID
@Binding var text: String
@EnvironmentObject var monster: Monster
var body: some View {
VStack {
HStack {
TextField("Enter text", text: $text)
Button {
monster.items.removeAll(where: { $0.id == id} )
} label: {
Text("Delete")
}
}
}
}
}