Search code examples
swift2uinavigationbaruisearchcontroller

Swift - NavigationBar issue with SearchController


I am having a problem with the NavigationBar when used with the SearchController.

If the NavigationBar translucent property is set to false the NavigationBar goes out of the screen when the SearchController is active. If the translucent property is set to true it works fine.

How could I fix it?

Code and Images below:

Swift file

import UIKit

class SelecionaPaisTableViewController: UITableViewController, UISearchResultsUpdating {

    //MARK: - Propriedades
    var paises = [PaisCodigo]()
    var paisesFiltrado = [PaisCodigo]()

    var controladorDeBusca: UISearchController!

    //MARK: - Métodos reescritos da View
    override func viewDidLoad() {
        super.viewDidLoad()

        //Dados dos países
        carregaDadosPaises()

        //Carrega configuração do SearchController
        configurarControladorDeBusca()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Métodos reescritos da Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if controladorDeBusca.active {
            return paisesFiltrado.count
        } else {
            return paises.count
        }
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("PaisCell", forIndexPath: indexPath)
        //let cell = tableView.dequeueReusableCellWithIdentifier("PaisCell", forIndexPath: indexPath) as UITableViewCell
        let pais: PaisCodigo

        if controladorDeBusca.active {
            pais = paisesFiltrado[indexPath.row]
        } else {
            pais = paises[indexPath.row]
        }

        cell.textLabel?.text = pais.nome + " (+" + String(pais.codigo) + ")"

        if pais.nome != pais.nomeIngles {
            cell.detailTextLabel?.text = pais.nomeIngles
        } else {
            cell.detailTextLabel?.text = ""
        }

        return cell
    }

    //MARK: - Métodos do UISearchResultsUpdating
    func updateSearchResultsForSearchController(searchController: UISearchController) {
        //paisesFiltrado.removeAll(keepCapacity: false)
    }

    //MARK: - Métodos
    func carregaDadosPaises() {
        let pais1 = PaisCodigo(nome: "Brasil", nomeIngles: "Brazil", codigo: 55)
        let pais2 = PaisCodigo(nome: "United States", nomeIngles: "United States", codigo: 1)

        paises += [pais1, pais2]

        //paisesTableView.reloadData()
    }

    func configurarControladorDeBusca() {
        //Configura Controlador de Busca
        controladorDeBusca = UISearchController(searchResultsController: nil)
        controladorDeBusca.searchResultsUpdater = self
        controladorDeBusca.dimsBackgroundDuringPresentation = false
        definesPresentationContext = true

        //Configura a barra do Controlador de busca
        controladorDeBusca.searchBar.placeholder = "Search country"
        controladorDeBusca.searchBar.sizeToFit()
        controladorDeBusca.searchBar.barTintColor = navigationController?.navigationBar.barTintColor
        controladorDeBusca.searchBar.translucent = true

        //UIBarButtonItem.appearanceWhenContainedInInstancesOfClasses([UISearchBar.self]).tintColor = UIColor.whiteColor()

        //let atts = [NSForegroundColorAttributeName: UIColor.whiteColor()]

        let atts = [
            NSFontAttributeName: UIFont(name:"GillSans-Bold", size:16)!,
            NSForegroundColorAttributeName: UIColor.whiteColor(),
            NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue
        ]

        controladorDeBusca.searchBar.setScopeBarButtonTitleTextAttributes(atts, forState: .Normal)

        //Adiciona a barra do Controlador de Busca a Table View
        tableView.tableHeaderView = controladorDeBusca.searchBar
    }
}

enter image description here enter image description here


Solution

  • When not using a translucent NavigationBar you need to ensure that both adjusts scroll view insets and extend edges under opaque bars are set to true on your ViewController.

    Link of the answer: Setting NavigationController's NavigationBar translucent property to false causes extra padding