Sham Dhiman
Sham Dhiman

Reputation: 1556

UISearchBar Height Automatic Size Change Swift

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.

Upvotes: 0

Views: 1164

Answers (1)

Abhishek Jadhav
Abhishek Jadhav

Reputation: 706

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
    }

Upvotes: 2

Related Questions