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 adding a programatically UISearchbar but I am really confused about why shows extra space from the top like the second image. but when I write the UISearchbar changes our position like the 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.

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59
  • 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
  • 706
  • 5
  • 12