How to set left and right paddings for UISearchController searchBar?

817 Views Asked by At

I'm using system searchBar via UISearchController in my Swift app. What is the correct way to set left and right padding to searchTextField? I need paddings for searchTextField itself, not just for text inside the field

I tried to set searchFieldBackgroundPositionAdjustment property(https://developer.apple.com/documentation/uikit/uisearchbar/1624320-searchfieldbackgroundpositionadj), but it doesn't change anything.

Here is a piece of code

    let searchController = UISearchController(searchResultsController: nil)
    navigationItem.searchController = searchController
    navigationItem.hidesSearchBarWhenScrolling = true
    definesPresentationContext = true
    
    searchController.searchResultsUpdater = self
    searchController.hidesNavigationBarDuringPresentation = false
    
    let textField = searchController.searchBar.searchTextField
    textField.font = UIFont(name: "AvenirNext-Regular", size: 16.0)

    // doesn't work
    searchController.searchBar.searchFieldBackgroundPositionAdjustment = UIOffset(horizontal: 100, vertical: 0)

See on screenshot what I'm trying to achive - make searchBar width equals to tabs panel in the bottom.

enter image description here

Thanks in advance!

1

There are 1 best solutions below

6
Vikas Saini On

Try this :

    let searchController = UISearchController(searchResultsController: nil)
           navigationItem.searchController = searchController
           navigationItem.hidesSearchBarWhenScrolling = true
           definesPresentationContext = true
           
           searchController.searchResultsUpdater = self
           searchController.hidesNavigationBarDuringPresentation = false
           
           let textField = searchController.searchBar.searchTextField
           textField.font = UIFont(name: "AvenirNext-Regular", size: 16.0)

         
        let directionalMargins = NSDirectionalEdgeInsets(top: 0, leading: 40, bottom: 0, trailing: 40)
        searchController.searchBar.directionalLayoutMargins = directionalMargins
        self.present(searchController, animated: true, completion: nil)

searchFieldBackgroundPositionAdjustment is used to set the offset of the search text field background in the search bar and not for search bar margin.