ios - 如何使用搜索 Controller 更新我的表 Controller 过滤?

标签 ios swift uitableview uisearchcontroller

我是 IOS 开发的新手,所以很难理解一些事情。

在我的应用中,当用户打开主屏幕时,我会显示一个任务列表和一个用于过滤任务的搜索。如果用户在我的搜索 Controller 中键入“星期一”,它应该只过滤星期一的任务。所有代码都运行良好,但我不知道这是否是正确的方法。

我有一个 TableView Controller ,它具有所有任务并在用户打开应用程序时显示。因此,用户首先应该看到的是他的所有任务。

当用户在表头打开搜索时,它应该过滤他的任务(从第一个表)并只显示与过滤器对应的任务。它也工作正常。

现在,我的问题。我有两张 table 。一个用于主视图 Controller ,另一个用于搜索 Controller 。 我必须为删除任务编写两次获取单元格和编辑样式的代码。

我做错了什么?我怎样才能对我的主表进行筛选并将所有内容保留在主表中,而不是将所有内容复制到第二个 Controller ?

谢谢

最佳答案

首先不需要用两个表来查找和显示,这根本不是一个好办法。您还应该在搜索 Controller 上寻找苹果文档。您应该使用 Search Bar 和 Search Display Controller 并在其 viewDidLoad 方法中实现以下代码

searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar

以下方法根据 searchText 过滤您的主数组,并将结果放入 filteredData 数组。

func filterContentForSearchText(searchText: String, scope: String = "All") {
     filteredData = array.filter { string in
     return     
     string.lowercaseString.containsString(searchText.lowercaseString)
  }

   tableView.reloadData()
}

为了让 ViewController 响应搜索栏,它必须实现 UISearchResultsUpdating。打开 ViewController.swift 并在主 ViewController 类之外添加以下类扩展:

extension MasterViewController: UISearchResultsUpdating {
  func updateSearchResultsForSearchController(searchController: UISearchController) {
    filterContentForSearchText(searchController.searchBar.text!)
  }
}

现在在您的 numberOfRowsInSection 和 cellForRowAtIndexPath 方法中执行以下操作

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
      if searchController.active && searchController.searchBar.text != "" {
    return filteredData.count
  }
  return array.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
  let string: String
  if searchController.active && searchController.searchBar.text != "" {
string = filteredData[indexPath.row]
  } else {
      string = array[indexPath.row]
   }
  cell.textLabel?.text = string
  return cell
}

有关更多详细信息,您可以访问以下网站。 https://www.raywenderlich.com/113772/uisearchcontroller-tutorial

关于ios - 如何使用搜索 Controller 更新我的表 Controller 过滤?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42089129/

相关文章:

ios - XCTest 中的屏幕比例因子

swift - 为什么调用UIDynamicBehavior的action closure后会出现memory leak/retain cycle?

ios - 如何快速使 SWRevealViewController 成为另一个 Controller 的子级

ios - iPad 上的 UIPopoverPresentationController

ios - 如何将变量值连接到 slider ?

ios - Build active architecture only for CocoaPods needs to NO in Xcode

ios - AFNetworking 2.0 HTTP POST 进展

iphone - 如何在iPhone应用程序的表格单元格中加载背景图像

ios - 如何与 UITableView 一起滚动标题?

ios - UITableView分页: inserting new cells while scrolling weird behavior