Created
April 18, 2020 08:40
-
-
Save smosko/c6c865e45c8827b6cc5fce5d722e0211 to your computer and use it in GitHub Desktop.
SwiftUI editable list
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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