简体   繁体   English

SwiftUI 带有字典的文本字段

[英]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.不幸的是,当我想使用 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)

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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