【问题标题】:Can you add UIViewRepresentable (UISearchBar) as a navigationBarItem? - SwiftUI您可以将 UIViewRepresentable (UISearchBar) 添加为 navigationBarItem 吗? - 斯威夫特用户界面
【发布时间】:2020-01-05 22:00:54
【问题描述】:

我正在像这样设置leadingtrailing navigationBarItems

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

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

搜索条码:

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
  }
}

【问题讨论】:

  • 根据我的发现,它现在可以正常工作,仅在 VStackList
  • 你的意思是我应该试试 VStack { List { SearchBar(text: $searchText) } }?这没有任何区别。
  • 不,我用VStack { SearchBar(text: $searchText) List { } }
  • 这不会编译,因为 List 必须返回一些东西。我将其更改为 VStack { SearchBar(text: $searchText) List { EmptyView() } } 但这仍然不起作用。

标签: swiftui


【解决方案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)
                }
            )
        }
    }
}

【讨论】:

  • 遗憾的是,这个解决方案有一些缺点,最明显的是您不能直接对每个字母进行更改:如果您执行Text("\(self.input)") 之类的操作,或者您有一个被过滤的List基于 $input,iOS 键盘在每个新字母后关闭。我猜这是因为 SwiftUI 更新了视图并决定同时关闭键盘。我还没有找到解决方法。
猜你喜欢
  • 1970-01-01
  • 2020-03-26
  • 2023-02-23
  • 2017-07-22
  • 2017-03-24
  • 2019-04-07
  • 2021-05-16
  • 2020-08-01
  • 1970-01-01
相关资源
最近更新 更多