73

新的 SwiftUI 框架似乎没有提供内置的搜索栏组件。我应该使用 UISearchController 并以某种方式包装它,还是应该使用简单的文本字段并根据文本字段输入更新数据?

编辑:当前的解决方法是使用 aTextField作为搜索栏。它工作得很好,但它没有搜索图标

在此处输入图像描述

import SwiftUI

struct Search : View {
  
  let array = ["John","Lena","Steve","Chris","Catalina"]
  
  @State private var searchText = ""
  
  var body: some View {
      NavigationView{
        List{
            TextField("Type your search",text: $searchText)
                .textFieldStyle(RoundedBorderTextFieldStyle())
            
            ForEach(array.filter{$0.hasPrefix(searchText) || searchText == ""}, id:\.self){searchText in
                Text(searchText)
            }
        }
        .navigationBarTitle(Text("Search"))
      }
  }
}

struct Search_Previews : PreviewProvider {
  static var previews: some View {
    Search()
  }
}

更新为与 Xcode 11.1 一起使用

4

7 回答 7

137

这是一个纯 swiftUI 版本,基于Antoine Weber对上述问题的回答以及我在这个博客这个 gist中找到的内容。它包含

  • 一个清除按钮,
  • 取消按钮,
  • 在列表中拖动时辞职键盘和
  • 选择搜索文本字段时隐藏导航视图。

在这些答案之后,可以使用 UIApplication 窗口上的方法来实现在列表中拖动时退出键盘。为了更容易处理,我在 UIApplication 上创建了一个扩展,并为此扩展创建了视图修饰符,最后是对 View 的扩展:

extension UIApplication {
    func endEditing(_ force: Bool) {
        self.windows
            .filter{$0.isKeyWindow}
            .first?
            .endEditing(force)
    }
}

struct ResignKeyboardOnDragGesture: ViewModifier {
    var gesture = DragGesture().onChanged{_ in
        UIApplication.shared.endEditing(true)
    }
    func body(content: Content) -> some View {
        content.gesture(gesture)
    }
}

extension View {
    func resignKeyboardOnDragGesture() -> some View {
        return modifier(ResignKeyboardOnDragGesture())
    }
}

所以最终退出键盘的修饰符只是一个必须放在列表中的修饰符,如下所示:

List {
    ForEach(...) {
        //...
    }
}
.resignKeyboardOnDragGesture()

带有示例名称列表的搜索栏的完整 swiftUI 项目代码如下。您可以将其粘贴到新的 swiftUI 项目的 ContentView.swift 中并使用它。


import SwiftUI

struct ContentView: View {
    let array = ["Peter", "Paul", "Mary", "Anna-Lena", "George", "John", "Greg", "Thomas", "Robert", "Bernie", "Mike", "Benno", "Hugo", "Miles", "Michael", "Mikel", "Tim", "Tom", "Lottie", "Lorrie", "Barbara"]
    @State private var searchText = ""
    @State private var showCancelButton: Bool = false

    var body: some View {

        NavigationView {
            VStack {
                // Search view
                HStack {
                    HStack {
                        Image(systemName: "magnifyingglass")

                        TextField("search", text: $searchText, onEditingChanged: { isEditing in
                            self.showCancelButton = true
                        }, onCommit: {
                            print("onCommit")
                        }).foregroundColor(.primary)

                        Button(action: {
                            self.searchText = ""
                        }) {
                            Image(systemName: "xmark.circle.fill").opacity(searchText == "" ? 0 : 1)
                        }
                    }
                    .padding(EdgeInsets(top: 8, leading: 6, bottom: 8, trailing: 6))
                    .foregroundColor(.secondary)
                    .background(Color(.secondarySystemBackground))
                    .cornerRadius(10.0)

                    if showCancelButton  {
                        Button("Cancel") {
                                UIApplication.shared.endEditing(true) // this must be placed before the other commands here
                                self.searchText = ""
                                self.showCancelButton = false
                        }
                        .foregroundColor(Color(.systemBlue))
                    }
                }
                .padding(.horizontal)
                .navigationBarHidden(showCancelButton) // .animation(.default) // animation does not work properly

                List {
                    // Filtered list of names
                    ForEach(array.filter{$0.hasPrefix(searchText) || searchText == ""}, id:\.self) {
                        searchText in Text(searchText)
                    }
                }
                .navigationBarTitle(Text("Search"))
                .resignKeyboardOnDragGesture()
            }
        }
    }
}



struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        Group {
           ContentView()
              .environment(\.colorScheme, .light)

           ContentView()
              .environment(\.colorScheme, .dark)
        }
    }
}

extension UIApplication {
    func endEditing(_ force: Bool) {
        self.windows
            .filter{$0.isKeyWindow}
            .first?
            .endEditing(force)
    }
}

struct ResignKeyboardOnDragGesture: ViewModifier {
    var gesture = DragGesture().onChanged{_ in
        UIApplication.shared.endEditing(true)
    }
    func body(content: Content) -> some View {
        content.gesture(gesture)
    }
}

extension View {
    func resignKeyboardOnDragGesture() -> some View {
        return modifier(ResignKeyboardOnDragGesture())
    }
}

最初显示时搜索栏的最终结果如下所示

在此处输入图像描述

当搜索栏像这样编辑时:

在此处输入图像描述

在行动:

在此处输入图像描述

于 2019-10-20T14:27:37.913 回答
21

原生搜索栏可以SwiftUI通过包装UINavigationController.

这种方法为我们提供了实现所有预期行为的优势,包括滚动时自动隐藏/显示、清除和取消按钮以及键盘中的搜索键等。

包装UINavigationController搜索栏还可以确保 Apple 对它们所做的任何新更改都会自动在您的项目中采用。

示例输出

单击此处查看实际执行情况

代码(包装 UINavigationController):

import SwiftUI

struct SearchNavigation<Content: View>: UIViewControllerRepresentable {
    @Binding var text: String
    var search: () -> Void
    var cancel: () -> Void
    var content: () -> Content

    func makeUIViewController(context: Context) -> UINavigationController {
        let navigationController = UINavigationController(rootViewController: context.coordinator.rootViewController)
        navigationController.navigationBar.prefersLargeTitles = true
        
        context.coordinator.searchController.searchBar.delegate = context.coordinator
        
        return navigationController
    }
    
    func updateUIViewController(_ uiViewController: UINavigationController, context: Context) {
        context.coordinator.update(content: content())
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(content: content(), searchText: $text, searchAction: search, cancelAction: cancel)
    }
    
    class Coordinator: NSObject, UISearchBarDelegate {
        @Binding var text: String
        let rootViewController: UIHostingController<Content>
        let searchController = UISearchController(searchResultsController: nil)
        var search: () -> Void
        var cancel: () -> Void
        
        init(content: Content, searchText: Binding<String>, searchAction: @escaping () -> Void, cancelAction: @escaping () -> Void) {
            rootViewController = UIHostingController(rootView: content)
            searchController.searchBar.autocapitalizationType = .none
            searchController.obscuresBackgroundDuringPresentation = false
            rootViewController.navigationItem.searchController = searchController
            
            _text = searchText
            search = searchAction
            cancel = cancelAction
        }
        
        func update(content: Content) {
            rootViewController.rootView = content
            rootViewController.view.setNeedsDisplay()
        }
        
        func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
            text = searchText
        }
        
        func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
            search()
        }
        
        func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
            cancel()
        }
    }
    
}

上面的代码可以按原样使用(当然可以修改以适应项目的特定需求)。

该视图包括用于“搜索”和“取消”的操作,当在键盘上点击搜索键并按下搜索栏的取消按钮时,它们分别被调用。该视图还包括一个SwiftUI作为尾随闭包的视图,因此可以直接替换NavigationView.

用法(在 SwiftUI 视图中):

import SwiftUI

struct YourView: View {
    // Search string to use in the search bar
    @State var searchString = ""
    
    // Search action. Called when search key pressed on keyboard
    func search() {
    }
    
    // Cancel action. Called when cancel button of search bar pressed
    func cancel() {
    }
    
    // View body
    var body: some View {
        // Search Navigation. Can be used like a normal SwiftUI NavigationView.
        SearchNavigation(text: $searchString, search: search, cancel: cancel) {
            // Example SwiftUI View
            List(dataArray) { data in
                Text(data.text)
            }
            .navigationBarTitle("Usage Example")
        }
        .edgesIgnoringSafeArea(.top)
    }
}

我也写了一篇关于这个的文章,可以参考它以获得额外的澄清。

我希望这会有所帮助,干杯!

于 2020-08-07T09:13:44.080 回答
20

这个 YouTube视频展示了它是如何完成的。它归结为:

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

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

然后代替

TextField($searchText)
              .textFieldStyle(.roundedBorder)

你用

SearchBar(text: $searchText)
于 2019-08-31T12:41:05.440 回答
14

iOS 15.0+

macOS 12.0+、Mac Catalyst 15.0+、tvOS 15.0+、watchOS 8.0+

searchable(_:text:placement:)

将此视图标记为可搜索,这会配置搜索字段的显示。https://developer.apple.com/

struct DestinationPageView: View {
    @State private var text = ""
    var body: some View {
      NavigationView {
        PrimaryView()
        SecondaryView()
        Text("Select a primary and secondary item")
     }
     .searchable(text: $text)
  }
}

观看此 WWDC 视频了解更多信息

在 SwiftUI 中打造搜索体验

于 2021-06-08T13:54:08.953 回答
2

许多 UIKit 组件目前没有 SwiftUI 等价物。为了使用它们,您可以创建一个包装器,如文档中所示。

基本上,您创建一个 SwiftUI 类,该类符合并UIViewRepresentable实现.makeUIViewupdateUIView

于 2019-06-07T16:49:58.783 回答
2

这适用于 SwiftUI 中的iOS 15.0+。

struct SearchableList: View {
    
    let groceries = ["Apple", "Banana", "Grapes"]
    @State private var searchText: String = ""
    
    var body: some View {
        NavigationView {
            List(searchResult, id: \.self) { grocerie in
                Button("\(grocerie)") { print("Tapped") }
            }
            .searchable(text: $searchText)
        }
    }
    
    var searchResult: [String] {
        guard !searchText.isEmpty else { return groceries }
        return groceries.filter { $0.contains(searchText) }
    }
}

struct SearchableList_Previews: PreviewProvider {
    static var previews: some View {
        SearchableList().previewLayout(.sizeThatFits)
    }
}
于 2021-06-08T15:25:27.247 回答
1

我迟到了。但看起来你可以使用

searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search")

当您向下滚动时,displayMode.always将确保它坚持到 t0p

于 2022-01-19T02:07:32.270 回答