0

The problem:

Instead of adding a search bar(with a search and results controller) to a table view controller, I have added it to a regular view controller's navigation bar. At first everything seems fine, but when I click on the search bar the screen turns gray.

This is my code:

import UIKit

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating, UISearchBarDelegate{

    var schools = ["Saratoga", "Fremont", "Argonaut", "Redwood", "Foothill", "Miller", "Rolling Hills"].sorted()
    var filteredSchools = ["Saratoga", "Fremont", "Argonaut", "Redwood", "Foothill", "Miller", "Rolling Hills"].sorted()

    var searchController: UISearchController!
    var resultsController: UITableViewController!

    override func viewDidLoad() {
        super.viewDidLoad()

        resultsController = UITableViewController()
        searchController = UISearchController(searchResultsController: resultsController)

        resultsController.tableView.delegate = self
        resultsController.tableView.dataSource = self
        searchController.searchResultsUpdater = self

        self.view.addSubview(searchController.searchBar)
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: searchController.searchBar)
    }

    func updateSearchResults(for searchController: UISearchController) {
        let currText = searchController.searchBar.text ?? ""
        filteredSchools = schools.filter({ (school) -> Bool in
            if school.contains(currText){
                return true
            }
            return false
        })
        resultsController.tableView.reloadData()
    }

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        cell.textLabel?.text = filteredSchools[indexPath.row]
        return cell
    }

}
Nikhil Sridhar
  • 1,670
  • 5
  • 20
  • 39
  • Possible duplicate of [Attempting to load the view of a view controller while it is deallocating... UISearchController](https://stackoverflow.com/questions/32282401/attempting-to-load-the-view-of-a-view-controller-while-it-is-deallocating-uis) – Mr. Xcoder Jun 30 '17 at 20:18
  • I edited my question. The problem still exists but I was able to fix the warning. – Nikhil Sridhar Jun 30 '17 at 20:44

1 Answers1

1

Add these lines in viewDidLoad:

resultsController.tableView.backgroundColor = UIColor.clear
searchController.hidesNavigationBarDuringPresentation = false

Your Navigation Bar is hiding that's all.

If you don't want the gray tint:

searchController.dimsBackgroundDuringPresentation = false
nighttalker
  • 896
  • 6
  • 13