可以将UIViewRepresentable(UISearchBar)添加为navigationBarItem吗? -SwiftUI

时间:2019-12-27 16:41:21

标签: swiftui

我正在这样设置leadingtrailing navigationBarItems

.navigationBarItems(leading: SearchBar(text: $searchText), trailing: rightTopBarItems())

trailing项目显示正常,但没有出现SearchBar。是否可以将UIViewRepresentable添加为navigationBarItem?我在文档中找不到任何内容。

SearchBar代码:

import SwiftUI

struct SearchBar: 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
    }
  }

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

  func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
    let searchBar = UISearchBar(frame: .zero)
    searchBar.delegate = context.coordinator
    searchBar.autocapitalizationType = .none
    searchBar.searchBarStyle = UISearchBar.Style.minimal
    return searchBar
  }

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

1 个答案:

答案 0 :(得分:1)

我有同样的问题。 因此,我放弃添加UIViewRepresentable并决定直接使用TextField

我希望这能达到您的目的。

struct SearchTextField: View {
    @State var input: String = ""
    @Binding var searchText: String

    var body: some View {
        HStack {
            Image(systemName: "magnifyingglass")
            TextField("Search word", text: $input, onCommit: {
                self.searchText = self.input
            })
        }
    }
}

final class SearchViewModel: ObservableObject {
        @Published var searchText = ""
}

struct ContentView: View {
    @ObservedObject var viewModel = SearchViewModel()
    var body: some View {
        NavigationView {
            Text("Hello")
            .navigationBarTitle(Text(""), displayMode: .inline)
            .navigationBarItems(leading:
                HStack {
                    SearchTextField(searchText: $viewModel.searchText)
                }
            )
        }
    }
}