0
votes

A tableview controller is embedded into a navigation controller. I programmatically added a search bar to the tableview controller's navigation bar. I only changed the navigation bar Background color into something different than Default (purple) - all the rest I left default.

class TableViewController: UITableViewController {
    let searchController = UISearchController(searchResultsController: nil)
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationItem.hidesSearchBarWhenScrolling = true
        navigationItem.searchController = searchController
    }
}

Code above is reduced to bare minimum for demonstration purpose.
All done with Xcode 11 (11A420a).

I ran the project in iOS 12.0 and 13.0 simulators and devices.

  • iOS 13.0
    The search bar shows upon start.
    Navigation bar background color is correctly presented.
    While scrolling, navigation bar background color remains correct.

With iOS 13.0, all works as expected!

  • iOS 12.0
    The search bar doesn't show upon start.
    Navigation bar background color is correctly presented.
    While scrolling, navigation bar background color goes white as soon search bar is visible.

I tried to change all kind of color setting in storyboard as well as properties programmatically. I didn't succeed in changing the navigation bar background color when search bar is visible.

It seems (?!) that the navigation bar foreground looses transparency when search bar becomes visible.

If I use a Bar Tint color of the navigation bar (!= Default), all works as expected (and as with iOS 13.0), but I loose the gradient effect, which I would like to keep.

What did I miss?
How can I avoid this?
Bug?

search bar not visible search bar visible

2

2 Answers

1
votes

I had some luck with the navigationItem.scrollEdgeAppearance property when facing a similar problem. For example:

vc.navigationItem.scrollEdgeAppearance?.backgroundColor = .red

This is only available on iOS 13 though.

Here's what I ended up doing to get correct colors in the navigation bar while allowing the search controller's scroll bar to hide during scroll:

if #available(iOS 13.0, *) {

    let blurEffect = UIBlurEffect(style: .systemUltraThinMaterial)
    navbar.standardAppearance.backgroundEffect = blurEffect
    navbar.standardAppearance.backgroundColor = appMainColor.withAlphaComponent(0.75)
    navbar.standardAppearance.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white]
    navbar.compactAppearance = nil
    navbar.scrollEdgeAppearance = navbar.standardAppearance.copy()

    navitem.standardAppearance = nil
    navitem.compactAppearance = nil
    navitem.scrollEdgeAppearance = nil
}
0
votes

I don't know if it is the look you're going for but I found if you disable hideSearchBarWhenScrolling the background stops changing color. However, the search bar is always there.

Add this to viewDidLoad():

navigationItem.hidesSearchBarWhenScrolling = false