Search code examples
swiftuinavigationbarios9uisearchbar

Navigation Bar and Search Controller


I want my navbar and search bar to be the same color. I also want to get rid of the hairline between them but that seems a minor issue compared to the first one. The navbar attributes are set this way:

self.navigationController?.navigationBar.barTintColor = ColorHelper.sharedInstance.LightPink()
    if let navBarFont = UIFont(name: "HelveticaNeue-Light", size: 25.0) {
        let navBarAttributesDictionary: [String: AnyObject]? = [
            NSForegroundColorAttributeName: UIColor.whiteColor(),
            NSFontAttributeName: navBarFont
        ]
        self.navigationController?.navigationBar.titleTextAttributes = navBarAttributesDictionary
 }

The search bar attributes:

searchController.searchResultsUpdater = self
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
searchController.searchBar.placeholder = "Search for new friends"
tableView.tableHeaderView = searchController.searchBar
searchController.searchBar.backgroundColor = ColorHelper.sharedInstance.LightPink()
searchController.searchBar.barTintColor = ColorHelper.sharedInstance.LightPink()
searchController.searchBar.backgroundImage = UIImage()

The result

It may seem as my ColorHelper returns different values for LightPink but it doesn´t. I've checked the color HEX-values and it's the navbar that is showing the color improperly, a bit lighter than it actually is. Any ideas why? Altering .barStyle did not change anything.


Solution

  • Same color:

    I had the same problem and I solved it by setting backroundImage for my UISearchBar (1x1 pixel image with the same color as my UINavigationBar). And pay attention to transluent field – it must have the same value as your UINavigationBar

    Separator:

    To remove separator between navigation and search bar you can use this code in your AppDelegate

    UINavigationBar.appearance().setBackgroundImage(UIImage(), forBarMetrics: .Default)
    UINavigationBar.appearance().shadowImage = UIImage()
    

    But it works only if you set transluent field to false