-1

Im trying to set an left to right aligned searchbar text programmatically but it seems like it adds the text on the opposite direction (like english) and then there are no results from the search. thanks for anyone helping.

Erik17
  • 33
  • 4

4 Answers4

5

Did you try to make it in such way?

 searchbar.semanticContentAttribute = .forceRightToLeft

Also make sure you are using right-to-left language for simulator/device keyboard layout when testing.

It's helpful to disable "Connect hardware keyboard" (Hardware -> Keyboard -> "Connect hardware keyboard" -> remove checkmark) when testing on Simulator, in order to see keyboard layout.

phantom_2
  • 543
  • 7
  • 14
  • you can also add: if let tfOfSearchBar = self.searchBar.value(forKey: "searchField") as? UITextField { tfOfSearchBar.textAlignment = .right } – Hen Shabat Aug 12 '19 at 21:36
2
    var searchTextField: UITextField
    if #available(iOS 13.0, *) {
        searchTextField = searchController?.searchBar.searchTextField as! UITextField
    } else {
        searchTextField = searchController?.searchBar.value(forKey: "searchField") as! UITextField
    }
    searchTextField.textAlignment = .right
Oz Shabat
  • 1,434
  • 17
  • 16
0

You can add search bar for right alignment like below-

    func addSearchController() {
        let searchController = UISearchController(searchResultsController: nil)
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Search"
        navigationItem.searchController = searchController
        definesPresentationContext = true
        let searchTextField: UITextField = searchController.searchBar.value(forKey: "_searchField") as! UITextField
        searchTextField.textAlignment = .right
}

Let me know if it solves your issue.

Boudhayan
  • 750
  • 4
  • 15
  • It is always nice to have a comment if you have downvoted. – Boudhayan Feb 14 '18 at 10:41
  • After searching everywhere, this is the only answer which I found. Nowhere else there is answer on how to change text alignment inside the search bar. – zeeshan Jan 26 '19 at 17:57
0

If you are using only UISearchbar you are change alignment by using below methods:

var searchTextField: UITextField
if #available(iOS 13.0, *) {
   searchTextField = searchBar.searchTextField as UITextField
} else {
    searchTextField = searchBar.value(forKey: "searchField") as! UITextField
}
    
searchTextField.textAlignment = .right
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83