'centering search controller vertically iOS

I added UISearchController programmatically with code

 let searchController = UISearchController(searchResultsController: nil)

 override func viewDidLoad() {
    super.viewDidLoad()

    searchController.searchResultsUpdater = self
    searchController.obscuresBackgroundDuringPresentation = false
    searchController.searchBar.placeholder = "Введіть значення для пошуку"
    searchController.searchBar.backgroundColor = .white
    navigationItem.searchController = searchController
    definesPresentationContext = true

}

But it seems that it is not centered vertically. How can I fix it?

enter image description here



Solution 1:[1]

Connected SearchController to TableView instead of NavigationItem

tableView.tableHeaderView = searchController.searchBar

Solution 2:[2]

It seems like a bug in iOS. For some reason at least on iOS 15 searchbar textfield frame has initial value of y = 1 but after you click on the field and then leave this field it will go to y = 8. Fixing the initial frame manually in viewDidLayoutSubviews solved this problem in my case:

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    searchController.searchBar.searchTextField.frame.origin.y = 8
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ioann Will
Solution 2 Leszek Szary