使用 UISearchBar 时的下拉菜单或弹出框

问题描述

我已经实现了一个 UISearchBarView

struct TextSearchBarView: UIViewRepresentable {
    
    @Binding var text: String
    
    class Coordinator: NSObject,UISearchBarDelegate {
        
        @Binding var text: String
        
        init(text: Binding<String>) {
            _text = text
        }
        
        func searchBar(_ searchBar: UISearchBar,textDidChange searchText: String) {
            text = searchText
            print("Coordinator",text)
        }
    }
    
    func makeCoordinator() -> TextSearchBarView.Coordinator {
        return Coordinator(text: $text)
    }
    
    func makeUIView(context: UIViewRepresentableContext<TextSearchBarView>) -> UISearchBar {
        let searchBar = UISearchBar(frame: .zero)
        searchBar.delegate = context.coordinator
        searchBar.searchBarStyle = .minimal
        return searchBar
    }
        
    func updateUIView(_ uiView: UISearchBar,context: UIViewRepresentableContext<TextSearchBarView>) {
        uiView.text = text
        print(uiView.text)
    }
}

我想显示一个弹出框来帮助用户在使用表单时过滤他正在搜索的内容:

  struct AddSightingView: View {
    @Environment(\.managedObjectContext) var viewContext
    @Environment(\.presentationMode) var presentationMode
    
    @State private var searchText = ""
    @State private var notes = ""
    @State private var showPopover: Bool = false

    let noteItems = ['Apple','Boy','Orange','Egg','Fish','Bee']
    
    var body: some View {
        NavigationView {
            Form {
                
                Section {
                    TextSearchBarView(text: $searchText) // <-- when the user search,want to show a popup view to show a list of possible noteItems. The user should be able to select them and it becomes the String the user selected and to be store in 'notes'
                }
                
                
                Section {
                    Button("Save") {
                        let newItem = Item(context: self.viewContext)
                        newItem.selectedText = "" // <-- the item the user selected during search. want to show as a popupview,should be one of the item appear in the list noteItems
                        
                        try? self.viewContext.save()
                        self.presentationMode.wrappedValue.dismiss()
                    }
                    
                }
            }
            .navigationBarTitle("Add Sighting")
        }
    }
}

我想做的是给用户一个表单,用户将输入一些内容作为文本字段。但是,那不是纯文本字段,而是具有搜索能力的文本字段。当用户输入时,文本字段根据用户输入过滤选择,只显示那些可能的选项供用户选择。用户确认选择并提交表单,更新我的 CoreData 对象。

我没有这样做,你可以看到上面代码中提到的注释。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)