Swift中的TableView搜索 [英] TableView search in Swift

查看:98
本文介绍了Swift中的TableView搜索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组:FirstTableArray(包括品牌名称)和SecondTableArray(包括模型).

I have two arrays: FirstTableArray (include name of brands) and SecondTableArray (include models).

我想添加搜索功能,通过该搜索可以通过名称的一部分找到手机的型号.

I want to add search through which the model of phone can be found by part of name.

import UIKit
import MessageUI

class FirstTableViewController: UITableViewController {

    var FirstTableArray = [String]()
    var SecondTableArray = [SecondTable]()

override func viewDidLoad() {

    super.viewDidLoad()

    self.navigationController?.navigationBar.isTranslucent = false
    self.navigationController?.navigationBar.barStyle = .black
    self.navigationController?.navigationBar.tintColor = UIColor.white

// First Table Array

    FirstTableArray = ["Apple", "Samsung"]

// Second Table Array

    SecondTableArray = [
    SecondTable(SecondTitle: ["iPhone 5s", "iPhone 6", "iPhone 6s"]),
    SecondTable(SecondTitle: ["Galaxy S4", "Galaxy S5", "Galaxy S6"]), 
    ]   
    }

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
    return FirstTableArray.count
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let Cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as UITableViewCell
    Cell.textLabel?.text = FirstTableArray[(indexPath as NSIndexPath).row]
    return Cell
    }

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    let indexPath : IndexPath = self.tableView.indexPathForSelectedRow!
    let DestViewController = segue.destination as! SecondTableViewController
    let SecondTableArrayTwo = SecondTableArray[(indexPath as NSIndexPath).row]
    DestViewController.SecondTableArray = SecondTableArrayTwo.SecondTitle
    } 
}

您能帮我吗?

推荐答案

我今天正在做同样的事情,发现本教程非常容易遵循:

I'm working through the same thing today and found this tutorial very easy to follow: https://github.com/codepath/ios_guides/wiki/Search-Bar-Guide

它将带您完成在Interface Builder中添加搜索栏,设置委托以及包括过滤结​​果的方法的步骤.

It will take you through the steps of adding the search bar in Interface Builder, setting up the delegate, and including a method to filter the results.

在iOS项目中,为用户提供搜索项目集合的方法是一项相当常见的任务.搜索栏是实现搜索行为的标准界面.

Providing a way for users to search through a collection of items is a fairly common task in iOS projects. A standard interface for implementing search behaviors is the search bar.

使用搜索栏的几种常见方法:

There are a few common ways to work with Search Bars:

  • 直接使用UISearchBar.这是最简单的使用方法 UISearchBars.如果您要设计,这可能会非常灵活 并编写自己的搜索界面,但不能提供 许多内置功能以及其他方法.

  • Directly using a UISearchBar. This is the most bare bones way to use UISearchBars. This can be extremely flexible if you want to design and program your own search interface, however does not provide as many built-in features as the other methods.

使用UISearchDisplayController帮助管理搜索界面. UISearchDisplayController允许您呈现标准搜索 与内置动画的接口.此方法强制您显示 在表格视图中搜索结果. -已弃用

Using a UISearchDisplayController to help manage a search interface. The UISearchDisplayController allows you to present a standard search interface with built-in animations. This method forces you to display search results in a table view. - DEPRECATED

使用UISearchController帮助管理搜索界面.
UISearchController是较新的控制器(仅在iOS 8+中可用)
可以帮助您使用任何一种视图来呈现搜索界面,以
显示搜索结果.

Using a UISearchController to help manage a search interface. The
UISearchController is a newer controller (available only in iOS 8+)
that helps you present a search interface using any kind of view to
display the search results.

本指南涵盖了使用这些类中的每一个的基本知识.实际上,这些类都没有实现查找与给定查询字符串匹配的项目的搜索"行为,因为确定哪些对象匹配将随特定领域的用例而变化(例如,在搜索人员"时,您可能只希望在其匹配对象上进行匹配)名称,而在通过电子邮件进行搜索时可能需要全文索引的搜索).您必须自己实现任何搜索/过滤行为.

This guide covers the very basics of working with each of these classes. None of these classes actually implements the "searching" behavior of finding items that match a given query string, since determining which objects match will vary with the domain specific use case (e.g. when searching for "people" you might want to match on just their names, whereas you may want a full-text pre-indexed search when searching through e-mails). You'll have to implement any search/filtering behavior yourself.

直接使用UISearchBars

搜索栏的核心不过是带有作用域控件,一些动画和几个按钮的精美文本字段.每个搜索栏都有一个委托,使您有机会响应用户的操作.最重要的委托方法是:

At its core, a search bar is nothing more than a glorified text field packaged with a scope control and some animations and a couple of buttons. Each search bar has a delegate that gives you an opportunity to respond to user actions. The most important delegate methods are:

  • textDidChange-大多数情况下,您将通过以下方式响应此事件 在用户输入内容时更新显示的搜索结果集 出一个查询
  • searchBarSearchButtonClicked-在某些情况下,如果搜索操作 速度很慢(例如,需要进行缓慢的API调用),您需要等待 直到用户在更新搜索之前点按搜索按钮 结果.
  • textDidChange - most of the time you'll respond to this event by updating the displayed set of search results as the user is typing out a query
  • searchBarSearchButtonClicked - in some cases if the search operation is slow (e.g. requires making a slow API call) you'll want to wait until the user taps the search button before updating the search results.

搜索表格的示例

我们从带有基本UITableView的单个视图应用程序开始.您可以像在任何其他控件中一样添加UISearchBar,方法是将一个UISearchBar拖到界面生成器中的视图控制器中,或者以编程方式添加它.

We start out with a single view application with a basic UITableView. You can add a UISearchBar as you would with any other control by dragging one to your view controller in interface builder or by programmatically adding it.

搜索栏的委托属性必须设置为实现UISearchBarDelegate的对象.通常,您使视图控制器实现UISearchBarDelegate并在viewDidLoad方法中设置searchBar.delegate = self.

The delegate property of search bar must be set to an object that implements UISearchBarDelegate. Typically you make your view controller implement UISearchBarDelegate and set searchBar.delegate = self in viewDidLoad method.

实现搜索行为的代码如下.我们维护一个额外的数组filteredData来表示与我们的搜索文本匹配的数据行.当搜索文本更改时,我们将更新filteredData并重新加载我们的表.

The code to implement the search behavior is as follows. We maintain an additional array filteredData to represent rows of data that match our search text. When the search text changes we update filteredData and reload our table.

class ViewController: UIViewController, UITableViewDataSource, UISearchBarDelegate {
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var searchBar: UISearchBar!

let data = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
    "Philadelphia, PA", "Phoenix, AZ", "San Diego, CA", "San Antonio, TX",
    "Dallas, TX", "Detroit, MI", "San Jose, CA", "Indianapolis, IN",
    "Jacksonville, FL", "San Francisco, CA", "Columbus, OH", "Austin, TX",
    "Memphis, TN", "Baltimore, MD", "Charlotte, ND", "Fort Worth, TX"]

var filteredData: [String]!

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.dataSource = self
    searchBar.delegate = self
    filteredData = data
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableCell", for: indexPath) as UITableViewCell
    cell.textLabel?.text = filteredData[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

// This method updates filteredData based on the text in the Search Box
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // When there is no text, filteredData is the same as the original data
    // When user has entered text into the search box
    // Use the filter method to iterate over all items in the data array
    // For each item, return true if the item should be included and false if the
    // item should NOT be included
    filteredData = searchText.isEmpty ? data : data.filter({(dataString: String) -> Bool in
        // If dataItem matches the searchText, return true to include it
        return dataString.range(of: searchText, options: .caseInsensitive) != nil
    })

    tableView.reloadData()
}
}

这是运行时的外观.请注意,搜索结果显示在同一表中,并且没有显示单独的搜索界面.

Here's what this looks like when running. Notice that the search results are displayed in the same table, and there is no presentation of a separate search interface.

搜索集合视图的示例

由于UISearchBar非常简单,因此可以将其与任意视图结合使用以构建自己的搜索界面.这就是与收藏夹视图配对的样子.

Since the UISearchBar is quite simple, it can be combined with any abitrary view to build your own search interface. Here's what it might look like paired with a collection view.

用于此目的的代码与使用表视图的情况基本相同.

The code for this is essentially the same as in the case with table views.

取消搜索并隐藏键盘

一旦用户点击搜索栏,键盘就会出现,并且您会注意到当您点击X时键盘不会消失.当用户点击搜索栏以及用户点击取消时,您可以显示取消"按钮. ,隐藏键盘.

Once user taps on search bar, the keyboard will appear, and you will notice that it won't go away when you tap on X. You can show Cancel button when user taps on search bar, and when user taps on Cancel, hide the keyboard.

UISearchBarDelegate有一个漂亮的searchBarTextDidBeginEditing方法,当用户开始编辑搜索文本时会调用该方法.您可以在该方法中显示取消"按钮:

There is a nifty searchBarTextDidBeginEditing method for UISearchBarDelegate that gets called when user starts editing search text. You can show Cancel button in that method:

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
        self.searchBar.showsCancelButton = true
}

当用户点击取消"按钮时,将调用委托的searchBarCancelButtonClicked方法.此时,您可以隐藏取消"按钮,清除搜索栏中的现有文本,并隐藏键盘,如下所示:

When user taps on cancel button, delegate's searchBarCancelButtonClicked method gets called. At this point, you can hide the Cancel button, clear existing text in search bar and hide the keyboard like this:

func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        searchBar.showsCancelButton = false
        searchBar.text = ""
        searchBar.resignFirstResponder()
}

使用UISearchControllers(iOS 8 +)

一种新的管理搜索界面表示的方法(仅在iOS 8及更高版本中可用)是通过UISearchController.该控制器处理了一些逻辑和动画,这些逻辑和动画为您提供了一个单独的搜索界面,同时仍然允许您指定搜索结果的显示方式.

A newer way to manage the presentation of a search interface (only available in iOS 8 and above) is via the UISearchController. This controller handles some of the logic and animation of presenting a separate search interface for you while still allowing you to specify how your search results are displayed.

搜索表格的示例

在界面构建器对象库中,目前没有用于UISearchController的内置对象.创建一个最简单的方法是以编程方式进行.这还将创建一个UISearchBar并将其设置搜索控制器的searchBar属性.您可以通过编程将此搜索栏添加到视图层次结构中.

There is currently no built-in object in the Interface Builder Object Library for a UISearchController. The easiest way to create one is to do it programatically. This also creates a UISearchBar and sets the search controller's searchBar property to it. You can add this search bar to your view hierarchy programatically.

要更新搜索结果,您必须实现UISearchResultsUpdating协议并设置搜索控制器的searchResultsUpdater属性.

In order to update your search results you'll have to implement the UISearchResultsUpdating protocol and set the search controller's searchResultsUpdater property.

除非您需要了解搜索界面外观附近的事件,否则无需实现UISearchControllerDelegate.

You don't need to implement the UISearchControllerDelegate unless you need to hook into the events around the presentation of the search interface.

将所有内容放在一起,代码看起来像这样.请注意,我们必须从updateSearchResultsForSearchController的搜索栏中读取搜索文本.需要注意的另一件事是,我们将该视图控制器的definePresentationContext属性设置为true.这意味着在显示搜索界面时,搜索控制器应使用此视图控制器的框架(与根视图控制器相对).在这种情况下,这意味着搜索界面将在载体栏上方展开.

Putting it all together the code looks like this. Notice that we have to read the search text from the search bar in updateSearchResultsForSearchController. One other thing to note is that we set this view controller's definesPresentationContext property to true. This means that the search controller should use this view controller's frame (as oppposed to the root view controller) when presenting the search interface. In this case it means that the search interface will expand above the carrier bar.

class ViewController: UIViewController, UITableViewDataSource, UISearchResultsUpdating {
    @IBOutlet weak var tableView: UITableView!

let data = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
    "Philadelphia, PA", "Phoenix, AZ", "San Diego, CA", "San Antonio, TX",
    "Dallas, TX", "Detroit, MI", "San Jose, CA", "Indianapolis, IN",
    "Jacksonville, FL", "San Francisco, CA", "Columbus, OH", "Austin, TX",
    "Memphis, TN", "Baltimore, MD", "Charlotte, ND", "Fort Worth, TX"]

var filteredData: [String]!

var searchController: UISearchController!

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = self
    filteredData = data

    // Initializing with searchResultsController set to nil means that
    // searchController will use this view controller to display the search results
    searchController = UISearchController(searchResultsController: nil)
    searchController.searchResultsUpdater = self

    // If we are using this same view controller to present the results
    // dimming it out wouldn't make sense. Should probably only set
    // this to yes if using another controller to display the search results.
    searchController.dimsBackgroundDuringPresentation = false

    searchController.searchBar.sizeToFit()
    tableView.tableHeaderView = searchController.searchBar

    // Sets this view controller as presenting view controller for the search interface
    definesPresentationContext = true
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("TableCell") as UITableViewCell
    cell.textLabel?.text = filteredData[indexPath.row]
    return cell
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return filteredData.count
}

func updateSearchResultsForSearchController(searchController: UISearchController) {
    if let searchText = searchController.searchBar.text {
        filteredData = searchText.isEmpty ? data : data.filter({(dataString: String) -> Bool in
            return dataString.rangeOfString(searchText, options: .CaseInsensitiveSearch) != nil
        })

        tableView.reloadData()
    }
}
}

这是运行时的外观.请注意,与在搜索显示控制器示例中不同,我们使用相同的表视图来显示搜索结果,而不是覆盖单独的表视图.但是,与仅使用搜索栏时不同,当转换到搜索界面时,我们仍然具有内置动画.

Here's what this looks like when running. Notice that unlike in the search display controller example, we are using the same table view to display the search results instead of overlaying of a separate table view. However, unlike when working with just the search bar, we still have the built in animation when transitioning to the search interface.

此外,当用户免费使用取消按钮时,您将获得显示取消按钮和隐藏键盘的逻辑.

Also, you get the logic to show Cancel button and hide keyboard when user taps on cancel button for free when you use this.

搜索集合视图的示例

我们可以像使用搜索控制器一样轻松地就地搜索集合视图.我们仍然展示了搜索界面,但是与使用搜索显示控制器时不同,我们不限于使用表格视图来显示搜索结果.

We can just as easily use the search controller to search a collection view in place. We still have the presentation of a search interface, but unlike when working with the search display controller we are not restricted to using a table view to display the search results.

此代码几乎与搜索上方表格视图时的代码相同.唯一显着的区别是我们必须在界面构建器中为搜索栏引入一个占位符视图,因为仍然存在一些古怪的做法,那就是将搜索控制器的搜索栏放置在集合视图的补充视图中.

The code for this is almost the same as when searching the the table view above. The only notable difference is that we had to introduce a placeholder view in interface builder for the search bar since there are still some quirks with placing a search controller's search bar inside a collection view's supplementary view.

class ViewController: UIViewController, UICollectionViewDataSource, UISearchResultsUpdating {
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var searchBarPlaceholder: UIView!
    ...
    override func viewDidLoad() {
        ...
        searchController.searchBar.sizeToFit()
        searchBarPlaceholder.addSubview(searchController.searchBar)
        automaticallyAdjustsScrollViewInsets = false
        definesPresentationContext = true
    }

    ...
}

导航视图中的搜索栏

一个常见的要求是将搜索栏放置在导航栏中.

A common requirement is to place the search bar inside the navigation bar.

可以在您的视图控制器的viewDidLoad中以编程方式对其进行如下配置.

This can be configured programatically in your view controller's viewDidLoad as follows.

直接与搜索栏一起使用时:

// create the search bar programatically since you won't be
// able to drag one onto the navigation bar
searchBar = UISearchBar()
searchBar.sizeToFit()

// the UIViewController comes with a navigationItem property
// this will automatically be initialized for you if when the
// view controller is added to a navigation controller's stack
// you just need to set the titleView to be the search bar
navigationItem.titleView = searchBar

使用搜索显示控制器:

searchDisplayController?.displaysSearchBarInNavigationBar = true

使用搜索控制器:

searchController.searchBar.sizeToFit()
navigationItem.titleView = searchController.searchBar

// By default the navigation bar hides when presenting the
// search interface.  Obviously we don't want this to happen if
// our search bar is inside the navigation bar.
searchController.hidesNavigationBarDuringPresentation = false

这篇关于Swift中的TableView搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆