Shawn Frank
Shawn Frank

Reputation: 5213

Presenting search controller from bar button hides elements in screen

I have an app which has a search bar that appears in the navigation bar and my set up is a hybrid of SwiftUI and UIKit.

I don't think this has bearing on the question at hand but here is my set up:

I have a custom hosting controller to control handle my searches, set up something like this:

class IndexSearchHostingController<Content: View>: UIHostingController<Content>, UISearchControllerDelegate, UISearchBarDelegate {

    init(rootView: Content) {
        super.init(rootView: rootView)
        addSearchBar()
    }

    private lazy var searchController: UISearchController = {
        let viewController =  UIHostingController(rootView: SearchResultsView())
        let search = UISearchController(searchResultsController: viewController)
        search.delegate = self
        search.showsSearchResultsController = true
        search.obscuresBackgroundDuringPresentation = true
        search.searchBar.delegate = self
       
        return search
    }()

    private func addSearchBar() {
        let image = UIImage(named: "iconName")?.withRenderingMode(.automatic)
        searchController.searchBar.placeholder = "Search"
        searchController.searchBar.setImage(image, for: .search, state: .normal)
        searchController.searchBar.autocapitalizationType = .none
        navigationItem.searchController = searchController
        navigationItem.hidesSearchBarWhenScrolling = false
    }
}

// Somewhere else in my code:
let viewController = IndexSearchHostingController(rootView: SwiftUIHomeView())
viewController.tabBarItem = tabBarItem.value
let navigationController = UINavigationController(rootViewController: viewController)

This works fine and I get the standard iOS search experience

However, because we want to add some more things to the navigation bar, it is getting quite crowded, I want to remove the search bar from the navigation bar and add a right bar button for search instead. Tapping this would launch the search experience.

While I could get this to work, the experience is not so nice.

I did not add the search controller to the navigation item and when I presented the searchController on the nav bar button tap, the search bar now hides some UI elements on my results screen.

SwiftUI UISearchController

How can I fix presenting a search controller such that when it is presented it does not hide UI from the results view

Upvotes: 0

Views: 24

Answers (0)

Related Questions