0

Here is what I am trying to do:

original image

The screenshot is taken from Iphone:

second image

I'm working on a simple app and add programatically uisearchbar but i am really confused why show extra space from top like second image . but when i write then uisearchbar changes our position like first image.

This is my code:

let searchController = UISearchController(searchResultsController: nil)

override func viewDidLoad() {
    super.viewDidLoad()

 self.searchController.obscuresBackgroundDuringPresentation = false
 self.searchController.searchBar.placeholder = "Search"
 self.searchController.searchBar.barStyle = .black
 self.searchController.searchBar.delegate = self
 self.definesPresentationContext = true
 if #available(iOS 11.0, *) {
 navigationItem.searchController = searchController
    } else {
        // Fallback on earlier versions
        navigationItem.titleView = searchController.searchBar
    }
   }

extension starControl: UISearchBarDelegate{

func searchBarTextDidBeginEditing(_ searchBar: UISearchBar)
{
    //Show Cancel
    searchBar.setShowsCancelButton(true, animated: true)
    searchBar.tintColor = .black
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String)
{

}

func searchBarSearchButtonClicked(_ searchBar: UISearchBar)  
{
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.resignFirstResponder()

    guard let term = searchBar.text , term.isEmpty == false else {

        return
    }
}

func searchBarCancelButtonClicked(_ searchBar: UISearchBar)
{
    searchBar.setShowsCancelButton(false, animated: true)
    searchBar.text = String()
    searchBar.resignFirstResponder()
 }
}

Can someone please explain to me how to solve this , i've tried to solve this issue but no results yet.

Any help would be greatly appreciated.

Thanks in advance.

Sam
  • 1
  • 15
  • 39
  • see this for help: https://stackoverflow.com/questions/46318022/uisearchbar-increases-navigation-bar-height-in-ios-11 – Anbu.Karthik Dec 26 '18 at 07:37

1 Answers1

2

This is latest swift4.2 code and latest functionality of search bar just put this function in controller and call from viewDidLoad.

func setupNavBar() {
        self.title = "Controller title"
        self.navigationController?.navigationBar.prefersLargeTitles = false
        self.navigationController?.navigationItem.largeTitleDisplayMode = .always
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchBar.delegate = self
        navigationItem.searchController = searchController
    }
Abhishek Jadhav
  • 686
  • 5
  • 12