SwiftUI从另一个视图捕获选择器值

SwiftUI从另一个视图捕获选择器值,swiftui,picker,Swiftui,Picker,我需要将搜索栏和nil值添加到picker。我想创建一个自定义选择器,并在任何地方使用它,以避免代码重复。我能够使用和代码创建一个选择器,但是我找不到如何捕获我在另一个视图中选择的值 此代码帮助我在选择器中搜索 struct SearchBar: UIViewRepresentable { @Binding var text: String var placeholder: String func makeUIView(context: UIViewRepre

我需要将搜索栏和nil值添加到picker。我想创建一个自定义选择器,并在任何地方使用它,以避免代码重复。我能够使用和代码创建一个选择器,但是我找不到如何捕获我在另一个视图中选择的值

此代码帮助我在选择器中搜索

    struct SearchBar: UIViewRepresentable {

    @Binding var text: String
    var placeholder: String

    func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
        let searchBar = UISearchBar(frame: .zero)
        searchBar.delegate = context.coordinator

        searchBar.placeholder = placeholder
        searchBar.autocapitalizationType = .none
        searchBar.searchBarStyle = .minimal
        return searchBar
    }

    func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
        uiView.text = text
    }

    func makeCoordinator() -> SearchBar.Coordinator {
        return Coordinator(text: $text)
    }

    class Coordinator: NSObject, UISearchBarDelegate {

        @Binding var text: String

        init(text: Binding<String>) {
            _text = text
        }

        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            text = searchText
        }
    }
}
在ContentView中

Form {
CustomPicker(items: countryArray, title: "Country", text: \Country.name, needOptional: true, needSearchBar: true)
}


如何在ContentView中捕获所选项目(可选)?

使用
@Binding
绑定您的项目

struct CustomPicker<Item>: View where Item: Hashable {
    let items: [Item]
    let title: String
    let text: KeyPath<Item, String>
    let needOptional: Bool
    let needSearchBar: Bool
    
    @Binding var item: Item? // <--Here
    @State var searchText: String = ""
    
    
    //-----Other code---------//

谢谢,我尝试了@Binding var item:item?=每次都是零。
Form {
CustomPicker(items: countryArray, title: "Country", text: \Country.name, needOptional: true, needSearchBar: true)
}
struct CustomPicker<Item>: View where Item: Hashable {
    let items: [Item]
    let title: String
    let text: KeyPath<Item, String>
    let needOptional: Bool
    let needSearchBar: Bool
    
    @Binding var item: Item? // <--Here
    @State var searchText: String = ""
    
    
    //-----Other code---------//
struct ContentView: View {
    
    @State private var selectedItem: Country? //<-- Here
    
    private let countryArray: [Country] = [.init(name: "A"), .init(name: "B")]
    
    var body: some View {
        Form {
            CustomPicker(items: countryArray, title: "Country", text: \Country.name, needOptional: true, needSearchBar: true, item: $selectedItem) // <-- Here
            if let selectedItem = selectedItem {
                Text(selectedItem.name)
            }
        }
    }
}