我有一个当前具有三个视图的应用程序,一个 ParentView,它是一个简单的列表,用户可以添加条目,一个 ContentView,它是一个模态表单,它收集信息以在 ParentView 中添加列表,以及一个 ChildPickerView,它重构了一些ContentView 中的代码得到了可怕的“编译器无法在合理的时间内对该表达式进行类型检查”消息。
我的问题是 ChildPickerView 包含需要保存的文本。它随着 3 个选择器的变化而更新。在 ContentView 中点击 Save 时,我试图将选择器返回的复合文本保存在 ChildPickerView 中。
我是 SwiftUI 的新手,所以可能会遗漏一些明显的东西,但这是我的代码。我尝试了 ContentView 中的 @State 对象和 ChildPickerView 中的 @Binding,但我的问题是构建复合文本视图,以跟踪我最终要保存并显示在 ParentView 列表中的选择器的状态。
这是我的代码(为简单起见,我只包含了 ContentView 和 ChildPickerView 的代码:
struct ContentView: View {
@State private var isCustomWidget: Bool = false
@State private var customWidgetName: String = ""
@State private var standardWidgetName: String = ""
var body: some View {
NavigationView {
Form {
Section(header: Text("WIDGET DETAILS")) {
Toggle(isOn: self.$isCustomWidget) {
Text("Custom")
}
if !self.isCustomWidget {
ChildPickerView(standardWidgetName: $standardWidgetName)
}
else
{
TextField("enter custom widget name", text: $customWidgetName)
}
}
Button(action: {
// we want to save either the standard widget name or custom widget name to our store
let str = self.isCustomWidget ? customWidgetName : standardWidgetName
print("saving \(str)")
})
{
Text("Save")
}
.navigationBarTitle("Add Widget")
}
}
}
}
struct ChildPickerView: View {
@State var selectedLengthIndex = 0
@State var selectedUnitsIndex = 0
@State var selectedItemIndex = 0
@Binding var standardWidgetName: String
var length: [String] = ["1","5","10","20","40","50","100","200"]
var units: [String] = ["Inches", "Centimeters"]
var items: [String] = ["Ribbon","Cord","Twine", "Rope"]
var body: some View {
List {
HStack {
Text("Widget Name")
Spacer()
let name =
"\(length[selectedLengthIndex])" + " " + " \(units[selectedUnitsIndex])" + " " + " \(items[selectedItemIndex])"
standardWidgetName = name //generates error on HStack -> Type '()' cannot conform to 'View'; only struct/enum/class types can conform to protocols
Text(name)
}
Picker(selection: $selectedLengthIndex, label: Text("Length")) {
ForEach(0 ..< length.count) {
Text(self.length[$0]).tag($0)
}
}
Picker(selection: $selectedUnitsIndex, label: Text("Unit of Measure")) {
ForEach(0 ..< units.count) {
Text(self.units[$0]).tag($0)
}
}
Picker(selection: $selectedItemIndex, label: Text("Item Type")) {
ForEach(0 ..< items.count) {
Text(self.items[$0]).tag($0)
}
}
}
}
}