ios 如何在Swiftui中创建自动完成的文本字段?

xmakbtuz  于 2023-06-07  发布在  iOS
关注(0)|答案(1)|浏览(157)

当在TextField中添加文本时。我们应该根据我们的文本类型获得建议,而不考虑大小写敏感性。当我们点击该建议时,应该添加数组。

gstyhher

gstyhher1#

当我们在textfield中键入内容时,我们将显示建议。如果我们在建议按钮上键入内容,我们将把该建议附加到selectedSuitableFor State变量和空textfield中,并将建议设置为false
宣告变数

@State var suggestions = ["Radiologist","Pathalogist","Surgeon","Orthopedic",
                          "Radiologist1","Pathalogist1","Surgeon1","Orthopedic1",
                          "Radiologist2","Pathalogist2","Surgeon2","Orthopedic2",
                          "Radiologist3","Pathalogist3","Surgeon3","Orthopedic3",
                          "Radiologist4","Radiologist5","Radiologist6","Radiologist7","Radiologist8",
                          "Radiologist9","Radiologist10"
]

@State var showSuggestions:Bool = false
@State var selectedSuitableFor:[String] = []
@State var selectedSuitableForItems:[[String]] = [[String]]()
VStack {
                    TextField("Suitable For", text: $suitableFor)
                        .onChange(of: suitableFor) { newValue in
                            showSuggestions = true
                        }
                        .textFieldStyle(RoundedBorderTextFieldStyle())
                    
                    if showSuggestions && !suitableFor.isEmpty {
                        ScrollView {
                            LazyVStack(alignment:.leading) {
                                ForEach(suggestions.filter({ $0.localizedCaseInsensitiveContains(suitableFor) }), id: \.self) { suggestion in
                                    ZStack {
                                        Button(action: {
                                            if (!selectedSuitableFor.contains(suggestion)){
                                                selectedSuitableFor.append(suggestion)
                                            }
                                            
                                            suitableFor = ""
                                            showSuggestions = false
                                        }) {
                                            Text(suggestion)
                                                .foregroundColor(.black)
                                        }
                                    }
                                }
                            }
                            .frame(maxHeight: 100)
                            .background(Color.white)
                        }
                    }
                }

相关问题