Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI Textfields inside Lists

Tags:

ios

swiftui

I want a list with rows, with each row having 2 Textfields inside of it. Those rows should be saved in an array, so that I can use the data in an other view for further functions. If the text in the Textfield is changed, the text should be saved inside the right entry in the array. You also can add new rows to the list via a button, which should also change the array for the rows.

The goal is to have a list of key value pairs, each one editable and those entries getting saved with the current text.

Could someone help me and/or give me hint for fixing this problem?

So far I have tried something like this:

// the array of list entries     
@State var list: [KeyValue] = [KeyValue()]
// the List inside of a VStack  
List(list) { entry in
    KeyValueRow(list.$key, list.$value)
}
// the single item
struct KeyValue: Identifiable {
    var id = UUID()

    @State var key = ""
    @State var value = ""
}
// one row in the list with view elements
struct KeyValueRow: View {

    var keyBinding: Binding<String>
    var valueBinding: Binding<String>

    init(_ keyBinding: Binding<String>, _ valueBinding: Binding<String>){
        self.keyBinding = keyBinding
        self.valueBinding = valueBinding
    }

    var body: some View {
        HStack() {
            TextField("key", text: keyBinding)
            Spacer()
            TextField("value", text: valueBinding)
            Spacer()
        }
    }
}

Also, about the button for adding new entries. Problem is that if I do the following, my list in the view goes blank and everything is empty again (maybe related: SwiftUI TextField inside ListView goes blank after filtering list items ?)

Button("Add", action: {
    self.list.append(KeyValue())
})
like image 527
Ruboka Avatar asked Sep 18 '25 15:09

Ruboka


2 Answers

Working code example for iOS 15

In SwiftUI, Apple recommends passing the binding directly into the List constructor and using a @Binding in the ViewBuilder block to iterate through with each element.

Apple recommends this approach over using the Indices to iterate over the collection since this doesn't reload the whole list every time a TextField value changes (better efficiency).

The new syntax is also back-deployable to previous releases of SwiftUI apps.

struct ContentView: View {
  @State var directions: [Direction] = [
    Direction(symbol: "car", color: .mint, text: "Drive to SFO"),
    Direction(symbol: "airplane", color: .blue, text: "Fly to SJC"),
    Direction(symbol: "tram", color: .purple, text: "Ride to Cupertino"),
    Direction(symbol: "bicycle", color: .orange, text: "Bike to Apple Park"),
    Direction(symbol: "figure.walk", color: .green, text: "Walk to pond"),
    Direction(symbol: "lifepreserver", color: .blue, text: "Swim to the center"),
    Direction(symbol: "drop", color: .indigo, text: "Dive to secret airlock"),
    Direction(symbol: "tram.tunnel.fill", color: .brown, text: "Ride through underground tunnels"),
    Direction(symbol: "key", color: .red, text: "Enter door code:"),
  ]

  var body: some View {
    NavigationView {
      List($directions) { $direction in
        Label {
          TextField("Instructions", text: $direction.text)
        }
      }
      .listStyle(.sidebar)
      .navigationTitle("Secret Hideout")
    }
  }
}

struct Direction: Identifiable {
  var id = UUID()
  var symbol: String
  var color: Color
  var text: String
}
like image 194
Pranav Kasetti Avatar answered Sep 21 '25 06:09

Pranav Kasetti


I am not sure what the best practice is keep a view up to date with state in an array like this, but here is one approach to make it work.

For the models, I added a list class that conforms to Observable object, and each KeyValue item alerts it on changes:

class KeyValueList: ObservableObject {

    @Published var items = [KeyValue]()

    func update() {
        self.objectWillChange.send()
    }

    func addItem() {
        self.items.append(KeyValue(parent: self))
    }
}
class KeyValue: Identifiable {

    init(parent: KeyValueList) {
        self.parent = parent
    }

    let id = UUID()
    private let parent: KeyValueList

    var key = "" {
        didSet { self.parent.update() }
    }
    var value = "" {
        didSet { self.parent.update() }
    }
}

Then I was able to simply the row view to just keep a single piece of state:

struct KeyValueRow: View {

    @State var item: KeyValue

    var body: some View {
        HStack() {
            TextField("key", text: $item.key)
            Spacer()
            TextField("value", text: $item.value)
            Spacer()
        }
    }
}

And for the list view:

struct TextFieldList: View {

    @ObservedObject var list = KeyValueList()

    var body: some View {

        VStack {
            List(list.items) { item in
                HStack {
                    KeyValueRow(item: item)
                    Text(item.key)
                }
            }
            Button("Add", action: {
                self.list.addItem()
            })

        }
    }
}

I just threw an extra Text in there for testing to see it update live.

I did not run into the Add button blanking the view as you described. Does this solve that issue for you as well?

like image 35
Ben Avatar answered Sep 21 '25 05:09

Ben