UISearchBar打开第二个没有结果的TableView

时间:2018-12-12 14:49:29

标签: ios swift

我有一个由Label,Button,SearchBar和TableView组成的ViewController。

这是视图的外观以及其流程(以及问题)。

Layouts

两个视图都有两个出口

@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从Core Data中获取数据,而不是过滤已经存在的数据。

获取数据可以正常工作,但是当键入任何内容时,即使搜索找到了数据,我也会看到另一个TableView,上面写着“无结果”。我可以单击“取消”,然后可以看到在普通TableView中获取的数据。

如何使该数据显示在自动打开的TableView中?

我也尝试将SearchBar分配为HeaderView的{​​{1}},但是这一切都消失了。

2 个答案:

答案 0 :(得分:1)

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

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    // Only update the top / Search Results table view here...
}

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

这是可行的解决方案(请记住,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)
    }
}

答案 1 :(得分:0)

UISearchController带有自己的搜索栏。它在UI编辑器中不可用(但已弃用的UISearchDisplayControllerUISearchBar仍然存在-如果可以,请不要使用它们)。您必须在代码中手动添加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()
    }
}