Search code examples
swiftuitableview

How do I create an editable table in SwiftUI?


how do I create a table on a view (see screenshot)? The user should be able to edit/ put some data into the textfields. I tried to recreate it by adding multiple VStacks and HStacks but my Xcode started complaining pretty fast.

I hope anyone can help me with this. It should be noted that there will be a few of such tables, so the user will be giving much input (just in case it has some effect on app performance). It will be inside of a ScrollView and a NavigationView.

Anyway, I appreciate any kind of Advice and thanks in Advance! Kind Regards

Screenshot


Solution

  • As always, @Yrb is absolutely right. And here is how it could look like:

    enter image description here

    struct ContentView: View {
        
        @State var inputFields: [String] = Array(repeating: "", count: 24)
        
        let columns = Array(repeating: GridItem(.flexible(minimum: 20)), count: 7)
        let rowTitles = ["A", "B", "C", "D"]
        
        var body: some View {
            
            LazyVGrid(columns: columns) {
                
                // first headline row
                Text("")
                ForEach(1..<7) { i in
                    Text("\(i)").bold()
                }
                
                // rows
                ForEach(0..<4) { row in
                    Text(rowTitles[row]).font(.title)
                    ForEach(0..<6) { col in
                        TextField("", text: $inputFields[row * 6 + col])
                            .background(
                                VStack {
                                    Spacer()
                                    Color.primary
                                        .frame(height: 1)
                                }
                            )
                    }
                }
            }
            .padding()
        }
    }