如何使 UITableViewController 符合 UISearchResultsUpdating 协议?

How do I make a UITableViewController conform to protocol UISearchResultsUpdating?

我有一个 UITableViewController class,我正在其中实施 UISearchController。我添加了以下代表:

class EmployeesTableView: UITableViewController, NSFetchedResultsControllerDelegate,UISearchResultsUpdating{

我正在导入 UIKitCoreData。我收到以下错误:

"Type 'CustomTableViewController' does not conform to protocol UISearchResultsUpdating"

我需要怎么做才能让控制器符合协议?

当您将协议添加到 class 定义时,最简单的方法是将鼠标悬停在协议名称上并使用命令单击其名称。这将拉出它的定义。对于协议定义,它们通常有紧随其后的方法。如果一个方法是必需的,它将位于顶部,如果它前面有可选的,那么为了符合要求,它不是必需的。

在`UISearchResultsUpdating 的情况下,它只有一个方法并且是必需的。只需复制该方法或多个方法,然后单击后退箭头返回您的 class。将这些方法粘贴到您的 class 中并实施它们。如果它们是可选方法(在这种情况下没有可选方法),请从前面删除可选方法。这是我从定义中复制的。

func updateSearchResultsForSearchController(searchController: UISearchController)

然后你更新它做你想做的事。

func updateSearchResultsForSearchController(searchController: UISearchController) {
    //do whatever with searchController here.
}

作为附加示例,命令单击 NSFechedResultsControllerDelegate。您会看到它没有必需的方法,但有很多可选的方法。这些信息通常也可以在文档中找到,但我发现 command + click 是找到我要查找的内容的最快方法。

Swift 3:

func updateSearchResults(for searchController: UISearchController) {

// code here

}

Swift 3.0

//Make sure to import UIKit
import Foundation
import UIKit

class ViewController: UIViewController, UISearchBarDelegate {

     var searchController = UISearchController()

     override func viewDidLoad() {
          //Setup search bar
          searchController = UISearchController(searchResultsController: nil)
          searchController.dimsBackgroundDuringPresentation = false
          definesPresentationContext = true
          //Set delegate
          searchController.searchResultsUpdater = self
          //Add to top of table view
          tableView.tableHeaderView = searchController.searchBar
     }
}
extension ViewController: UISearchResultsUpdating {
     func updateSearchResults(for searchController: UISearchController) {
          print(searchController.searchBar.text!)
     }
}