ios 如何根据文本字段输入更改选取器

n3schb8v  于 2023-02-01  发布在  iOS
关注(0)|答案(1)|浏览(124)

我当前正在尝试更改选取器将根据系列文本字段中的值显示的数据。我无法显示选取器,也没有收到任何错误,但收到此警告"非恒定范围:不是整数范围"。

struct ConveyorTracks: View {
    
    @State private var series = ""
    @State private var selectedMaterial = 0
    @State private var selectedWidth = 0
    @State private var positRack = false
    

    
    let materials8500 = ["HP", "LF", "Steel"]
    let widths8500 = ["3.25", "4", "6"]
    
    let materials882 = ["HP", "LF", "PS", "PSX"]
    let widths882 = ["3.25", "4.5", "6","7.5", "10", "12"]
        
    var materials: [String]   {
            if series == "8500" {
                return materials8500
            } else if series == "882" {
                return materials882
            } else {
                return []
            }
        }
        
    var widths: [String] {
        if series == "8500" {
            return widths8500
        } else if series == "882" {
            return widths882
        } else {
            return []
        }
    }
    
    var body: some View {
        VStack(alignment: .leading) {
            HStack {
                Text("Series:")
                TextField("Enter series", text: $series)
            }.padding()
            
            HStack {
                Text("Material:")
                Picker("Materials", selection: $selectedMaterial) {
                    ForEach(materials.indices) { index in
                        Text(self.materials[index])
                    }
                }.pickerStyle(SegmentedPickerStyle())

            }.padding()
            
            HStack {
                Text("Width:")
                Picker("Widths", selection: $selectedWidth) {
                    ForEach(widths.indices) { index in
                        Text(self.widths[index])
                    }
                }.pickerStyle(SegmentedPickerStyle())
            }.padding()
            
            HStack {
                Text("Positive Rack:")
                Toggle("", isOn: $positRack)
            }.padding()
        }
    }
}

struct ConveyorTrack_Previews: PreviewProvider {
    static var previews: some View {
        ConveyorTracks()
    }
}

我想根据系列文本字段中输入的材料和宽度值更改拾取器。
也许pickers不是最好的选择,我愿意接受任何建议。
谢谢!

8zzbczxx

8zzbczxx1#

ForEach(materials.indices)

需要

ForEach(materials.indices, id: \.self)

因为在ForEach中没有使用编译时常量。
一般来说,对于像这样的固定选择,如果您将所有内容都设置为枚举,并将枚举设置为Identifiable,则代码会简单得多。此简化示例仅显示一组物料,但您可以根据所选系列返回适用物料的数组(也可以是枚举?)

enum Material: Identifiable, CaseIterable {
    case hp, lf, steel
    var id: Material { self }
    var title: String {
        ... return an appropriate title
    }
}

@State var material: Material

...

Picker("Material", selection: $material) {
    ForEach(Material.allCases) {
        Text($0.title)
    }
}

相关问题