With iOS 11, searchBars are defaulting to a left aligned text. While this looks good with the rest of the native changes to iOS, it doesn't really fit my design, and I would like it to be center, as it was before.
I can't find any such alignment attributes on UISearchBar
. Am I missing something, or is it simply not possible? Do I have to create my own custom search bar e.g derived from a UITextField
to achieve this?
I had exactly the same problem - I'm struggling to understand why the default alignment would be changed without allowing us to easily set this back to centered.
The below works for me (Swift):
let placeholderWidth = 200 // Replace with whatever value works for your placeholder text
var offset = UIOffset()
override func viewDidLoad() {
offset = UIOffset(horizontal: (searchBar.frame.width - placeholderWidth) / 2, vertical: 0)
searchBar.setPositionAdjustment(offset, for: .search)
}
func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
let noOffset = UIOffset(horizontal: 0, vertical: 0)
searchBar.setPositionAdjustment(noOffset, for: .search)
return true
}
func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
searchBar.setPositionAdjustment(offset, for: .search)
return true
}
This is the only one that worked for me, Swift 4.2:
extension UISearchBar {
func setCenteredPlaceHolder(){
let textFieldInsideSearchBar = self.value(forKey: "searchField") as? UITextField
//get the sizes
let searchBarWidth = self.frame.width
let placeholderIconWidth = textFieldInsideSearchBar?.leftView?.frame.width
let placeHolderWidth = textFieldInsideSearchBar?.attributedPlaceholder?.size().width
let offsetIconToPlaceholder: CGFloat = 8
let placeHolderWithIcon = placeholderIconWidth! + offsetIconToPlaceholder
let offset = UIOffset(horizontal: ((searchBarWidth / 2) - (placeHolderWidth! / 2) - placeHolderWithIcon), vertical: 0)
self.setPositionAdjustment(offset, for: .search)
}
}
Usage:
searchBar.setCenteredPlaceHolder()
Result:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With