简体   繁体   中英

SwiftUI TextField with dictonary

I have several text fields and I would like to save all entries in a dictonary.

My dictonary:

@State var fieldInput: [String: Binding<String>] = [:]

My TextField:

TextField("Name", text: fieldInput["Name"]!)

Unfortunately, I always get this error when I want to access the view with the TextFields.

Fatak error: Unexpectedly found nuk while unwrapping an Optional value

Dictionary is not sequence container, so every entry in it not persistent on change, so you cannot bind to it, so this is not even allowed.

Here is possible approach

@State var fieldInput: [String: String] = [:]
@State private var name = ""

..

TextField("Name", text: $name)
   //.onReceive(Just(name)) {      // << iOS 13.+ (needs import Combine)
   .onChange(of: name) {
      fieldInput["Name"] = $0      // << here !!
   }
    struct ContentView: View {
    
    @State var fieldInput: [String: String] = [:]
    
    @State var value: String = String() {
        didSet {
            fieldInput["Name"] = value
        }
    }
    
    var body: some View {

        TextField("Enter your name here . . .", text: $value)

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM