Ios UISearchBar打开第二个TableView时没有结果

Ios UISearchBar打开第二个TableView时没有结果,ios,swift,Ios,Swift,我有一个ViewController,它由标签、按钮、搜索栏和TableView组成 下面是视图的外观,以及视图的流程和问题 我有两种观点 @IBOutlet weak var _searchBar: UISearchBar! @IBOutlet weak var _tableView: UITableView! // ... self._searchBar.delegate = self 搜索完成后,我会在此处捕获它: func searchBarSearchButtonClicked(_

我有一个ViewController,它由标签、按钮、搜索栏和TableView组成

下面是视图的外观,以及视图的流程和问题

我有两种观点

@IBOutlet weak var _searchBar: UISearchBar!
@IBOutlet weak var _tableView: UITableView!
// ...
self._searchBar.delegate = self
搜索完成后,我会在此处捕获它:

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    if let query = searchBar.text {
        print("Search query: \(query)")
        //Fetch data from CoreData and update datasource array
        self._tableView.reloadData()
    }
}
我使用NSPredicate从核心数据中获取数据,而不是过滤现有数据

获取数据工作正常,但是当键入任何内容时,我会看到另一个TableView,它只说没有结果,即使搜索正在查找数据。我可以单击Cancel,然后可以看到在普通TableView中获取的数据

如何在自动打开的TableView中显示此数据

我还尝试将搜索栏指定为TableView的HeaderView,但这使所有内容都消失了。

UISearchController自带了自己的搜索栏。它在UI编辑器中不可用,但不推荐使用的UISearchDisplayController和UISearchBar仍然存在-如果可以,请不要使用它们。您必须在代码中手动添加UISearchController并删除UISearchBar。这是值得的

最后,您的代码可能看起来像这样我这里不讨论TableView协议:

public class MyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchControllerDelegate  {

//Create the UISearchController (and sets the results to be displayed in the same controller
// (TableView?) as the searchable content)
let searchController = UISearchController(searchResultsController: nil)

public override func viewDidLoad() {
    super.viewDidLoad()

    //Sets self as the Search Controller's delegate
    searchController.delegate = self

    //Sets self to be responsible for updating the contents of the search result controller
    searchController.searchResultsUpdater = self        

    //Add the searchBar to the tableview header
    tableView.tableHeaderView = searchController.searchBar

    //Avoids the white area when pulling the seachbar (not mandatory but can help)
    tableView.backgroundView = UIView()

    //SearchBar aspect (same comment)
    searchController.searchBar.searchBarStyle = .minimal
    searchController.searchBar.placeholder = "Find the stuff"
    searchController.searchBar.setTextFieldColor(color: UIColor(hex: 0xBBBBBB, alpha: 1.0))


    //Do your other things
}

//MARK: UISearchControllerDelegate
public func didPresentSearchController(_ searchController: UISearchController) {
    searchController.searchBar.becomeFirstResponder()
}

// MARK: UISearchResultsUpdating
public func updateSearchResults(for searchController: UISearchController) {
    if let query = searchController.searchBar.text {
        print("Search query: \(query)")
        //Fetch data from CoreData and update datasource array
        self._tableView.reloadData()
    }
}

不确定是否已经实现了,但需要实现另一个UISearchBarDelegate方法:

如果您可以提供此功能的完整代码,我们可以为您提供更好的反馈

这是有效的解决方案记住,searchController应该是一个实例变量,而不是本地变量:

class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search for products or activities"
        searchController.searchBar.sizeToFit()
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.showsScopeBar = true
        searchController.searchBar.tintColor = UIColor.colorPrimary()
        searchController.searchBar.barTintColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
        searchController.searchBar.scopeButtonTitles = ["Products", "Activities"]
        searchController.searchBar.delegate = self
        searchController.searchBar.showsCancelButton = true
        self.definesPresentationContext = true

        // Prepare our tableView
        self._tableView.rowHeight = UITableView.automaticDimension
        self._tableView.separatorStyle = .none
        self._tableView.showsVerticalScrollIndicator = false
        self._tableView.delegate = self
        self._tableView.dataSource = self
        self._tableView.register(ProductViewCell.nib, forCellReuseIdentifier: ProductViewCell.identifier)
        self._tableView.register(ActivityViewCell.nib, forCellReuseIdentifier: ActivityViewCell.identifier)
        self._tableView.tableHeaderView = searchController.searchBar
    }

    // MARK: UITableViewDataSource Methods

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return NumberOfRows
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Return a Result Cell
    }
}


extension SearchViewController: UISearchBarDelegate, UISearchResultsUpdating {
    // MARK: UISearchControllerDelegate
    public func didPresentSearchController(_ searchController: UISearchController) {
        searchController.searchBar.becomeFirstResponder()
    }

    // MARK: UISearchResultsUpdating
    public func updateSearchResults(for searchController: UISearchController) {
        if let query = searchController.searchBar.text {
            print("Search query: \(query)")
            //Fetch data from CoreData and update datasource array
            fetchData()
            self._tableView.reloadData()
        }
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("search")
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print(searchText)
    }
}

你有UISearchController吗?没有,我在一些教程中看到过,但在UI编辑器中找不到该控件。我尝试手动创建它,但无法为其分配我自己的搜索栏。但如何访问搜索结果表?与“searchBarSearchButtonClicked”方法相同。以本例中的searchText参数为例,进行查询,并使用结果填充搜索结果表视图。这里的问题是表视图确实填充了,但搜索结果表视图为空。如何获取对搜索结果表的引用?如果您使用的是UISearchController-我相信您必须为搜索结果创建和配置单独的表视图UISearchDisplaycontroller,它已过时,用于具有searchResultsTableView属性,但新类没有。或者,您可以对这两种情况使用相同的表视图,但不确定是否可以这样做,因为我看到您还有一个分段控件。”let searchController'应该是实例变量,而不是本地变量。您这样做的方式是错误的,它将在退出您声明它的方法后很快被释放。
class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search for products or activities"
        searchController.searchBar.sizeToFit()
        searchController.searchBar.searchBarStyle = .minimal
        searchController.searchBar.showsScopeBar = true
        searchController.searchBar.tintColor = UIColor.colorPrimary()
        searchController.searchBar.barTintColor = #colorLiteral(red: 0.921431005, green: 0.9214526415, blue: 0.9214410186, alpha: 1)
        searchController.searchBar.scopeButtonTitles = ["Products", "Activities"]
        searchController.searchBar.delegate = self
        searchController.searchBar.showsCancelButton = true
        self.definesPresentationContext = true

        // Prepare our tableView
        self._tableView.rowHeight = UITableView.automaticDimension
        self._tableView.separatorStyle = .none
        self._tableView.showsVerticalScrollIndicator = false
        self._tableView.delegate = self
        self._tableView.dataSource = self
        self._tableView.register(ProductViewCell.nib, forCellReuseIdentifier: ProductViewCell.identifier)
        self._tableView.register(ActivityViewCell.nib, forCellReuseIdentifier: ActivityViewCell.identifier)
        self._tableView.tableHeaderView = searchController.searchBar
    }

    // MARK: UITableViewDataSource Methods

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return NumberOfRows
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Return a Result Cell
    }
}


extension SearchViewController: UISearchBarDelegate, UISearchResultsUpdating {
    // MARK: UISearchControllerDelegate
    public func didPresentSearchController(_ searchController: UISearchController) {
        searchController.searchBar.becomeFirstResponder()
    }

    // MARK: UISearchResultsUpdating
    public func updateSearchResults(for searchController: UISearchController) {
        if let query = searchController.searchBar.text {
            print("Search query: \(query)")
            //Fetch data from CoreData and update datasource array
            fetchData()
            self._tableView.reloadData()
        }
    }

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        print("search")
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        print(searchText)
    }
}