Skip to content

Instantly share code, notes, and snippets.

@smosko
Created April 18, 2020 08:40
Show Gist options
  • Save smosko/c6c865e45c8827b6cc5fce5d722e0211 to your computer and use it in GitHub Desktop.
Save smosko/c6c865e45c8827b6cc5fce5d722e0211 to your computer and use it in GitHub Desktop.
SwiftUI editable list
import SwiftUI
class Item: ObservableObject, Identifiable {
let id = UUID()
@Published var name = ""
@Published var value = ""
}
struct ContentView: View {
@State private var items: [Item] = []
var body: some View {
ListView(items: $items)
}
}
struct ListView: View {
@Binding var items: [Item]
var body: some View {
Form {
ForEach(items) {
ItemView(item: $0)
}
.onDelete {
self.items.remove(atOffsets: $0)
}
Button("Add item") {
self.items.append(Item())
}
}
}
}
struct ItemView: View {
@ObservedObject var item: Item
var body: some View {
HStack {
TextField("Name", text: $item.name)
TextField("Value", text: $item.value)
.multilineTextAlignment(.trailing)
.foregroundColor(.secondary)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment