Search code examples
iosswiftuisearchcontroller

how to make the UISearchController() hidden by default?


I have UISearchController() added to my UIViewController as the following:

class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating  { 

let tableData = ["Here's", "to", "the", "crazy"]
var filteredTableData = [String]()
var resultSearchController = UISearchController()

@IBOutlet var tableView: UITableView!


override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.dataSource = self
    self.tableView.delegate = self
    self.resultSearchController = ({
        let controller = UISearchController(searchResultsController: nil)
        controller.searchResultsUpdater = self
        controller.dimsBackgroundDuringPresentation = false
        controller.searchBar.sizeToFit()

        self.tableView.tableHeaderView = controller.searchBar

        return controller
    })()

    // Reload the table
    self.tableView.reloadData()
}

... TableView functions ...

func updateSearchResultsForSearchController(searchController: UISearchController)
    {
        filteredTableData.removeAll(keepCapacity: false)

        let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text)
        let array = (tableData as NSArray).filteredArrayUsingPredicate(searchPredicate)
        filteredTableData = array as! [String]

        self.tableView.reloadData()
    }

I'm trying to make the search bar hidden by default, in other words, make it similar to the search bar style the "Notes" iPhone application where you have to scroll the tableView down to show the search bar. Is there a way I can achieve this? Like adding add a negative constraint that makes it hidden under the navigation bar when the ViewController loads?


Solution

  • Found a very simple solution to hide the search bar by default, I found the answer here

    I just needed to add this line in the viewDidLoad() :

    tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), atScrollPosition: UITableViewScrollPosition.Top, animated: false)
    

    Updated to Swift 3.0 syntax:

    tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: false)