0

I placed searchController's searchBar in navigationItem as the titleView as follows:

self.navigationItem.titleView = self.searchController.searchBar;

Although it fits perfectly when it is not selected (cancel item is not shown), if it becomes first responder and cancel item appears next to the searchBar, it slides under of the navigationItem slightly. You can see the result below:

Position of searchBar in navigationItem

How can I fix this? Is there a workaround?

Dorukhan Arslan
  • 2,676
  • 2
  • 24
  • 42

2 Answers2

0

You should use self.navigationItem.searchController instead of self.navigationItem.titleView.

self.navigationItem.searchController = self.searchController;

Learn more here https://developer.apple.com/documentation/uikit/uinavigationitem/2897305-searchcontroller

trungduc
  • 11,926
  • 4
  • 31
  • 55
-1

Use below code

if #available(iOS 11.0, *) {
     navigationItem.searchController = searchController
} else {
     // Fallback on earlier versions
     navigationItem.titleView = searchController?.searchBar
}
Rishi Chaurasia
  • 520
  • 4
  • 18