ios 在SwiftUI中使用动态表单和字段状态

mcvgt66p  于 2023-01-14  发布在  iOS
关注(0)|答案(2)|浏览(105)

我有点不知道如何使用动态表单的状态。我肯定不能为每个字段创建状态,因为我不知道有多少字段,因为这些表单基本上是从JSON响应构建的。
这是我现在所拥有的,也是我想要改变的,最初我为每个字段创建了一个状态,那时表单还没有动态构建,现在我陷入了如何继续的困境。
我想过使用字典,但我不知道这是一个多么好的解决方案。

@State var textfieldText: String = ""
    @State var SKU: String = ""
    @State private var showScanner: Bool = false
    var currentForm: FormModel
    @State var RecordDate: Date = Date.now
    @State var Formresponse: [String: Any] = [:]//This one is set to any because the value can vary from a string to [] to even a whole object

如何呈现窗体:

ForEach(currentForm.item, id:\.idf) { it in
                
                        if (!it.questionItem.hidden)
                        {
                            switch it.questionItem.questionType {
                        case .dateQuestion :
                                    DateField(title: it.title, currentDate: $RecordDate)
                        case .choiceQuestion:
                            Text("choice question")
                        case .scannerQuestion:
                            ScannerField(title: it.title, SKU: $SKU, showScanner: $showScanner)
                            
                        case .textQuestion:
                            TextQuestionField(title: it.title, email: currentForm.owner, text: $textfieldText)
                            }
                        }
                    
                }

我最终将不得不以字典的形式提交这些数据,这就是为什么我考虑使用Dict [“fieldID”:“FieldInput”,“fieldId2”:“FieldInput2”..]

ryevplcw

ryevplcw1#

为问题类型定义枚举

enum FormItemType {
   case dataQuestion
   case choiceQuestion
   case scannerQuestion
   case textQuestion
}

定义问题类型的项目模型:

struct FormItemModel : Identifiable {
    var type : FormItemType
    var itemObject : Any
    var userInput : String?
    let id : UUID
}

定义表单视图模型:

final class FormModel : ObservableObject {        
    @Published var items : [FormItemModel] = []
}

和视图:

struct ContentView: View {
    
    @ObservedObject var formViewModel: FormModel
    
    @Binding var currentInput : String
    
    var body: some View {
        
        List {
            ForEach(formViewModel.items, id: \.id, content: { item in
                
                switch item.type {
                case .dataQuestion:
                    Text(item.itemObject as? String ?? "")
                    
                case .scannerQuestion:
                    Text("\(item.itemObject as? Int ?? 0 )")
                    
                case .choiceQuestion:
                    if let dic = item.itemObject as? [String:String]{
                        VStack{
                            Text(dic["Q"]!)
                            Text(dic["A1"]!)
                            Text(dic["A2"]!)
                            Text(dic["A3"]!)
                        }
                    }
                    
                case .textQuestion:
                    
                    VStack{
                        Text(item.itemObject as? String ?? "")
                        TextEditor(text: $currentInput)
                    }
                }
            })//ForEach
        }//List
    }
}//View

下面是表单的虚拟值:

items = [FormItemModel(type: .textQuestion, itemObject: "Tell Me About Yourself...", id: UUID()),
             FormItemModel(type: .choiceQuestion,
                           itemObject: ["Q":"How much is 1+1?", "A1":"1", "A2":"2", "A3":"3"],
                           id: UUID()),
             FormItemModel(type: .scannerQuestion, itemObject: 1110111011, id: UUID())
    ]

结果是:

roejwanj

roejwanj2#

我认为你只需要一个State,这是针对formResponse的,你可以把它作为Binding传递给每个输入字段视图,在该视图中你可以创建一个自定义的Binding来获取和设置formResponse的答案,类似于这样:

struct FormFieldInputView: View {
    @Binding var formResponse: [String: Any]
    let field: String

    var body: some View {
        TextField(field, text: Binding(
            get: {
                formResponse[field] as? String ?? ""
            },
            set: { newValue in
                formResponse[field] = newValue
            })
        )
    }
}

相关问题