Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center placeholder text in UISearchBar iOS 11

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?

like image 344
Sti Avatar asked Jun 18 '17 17:06

Sti


2 Answers

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
}
like image 55
Ben Avatar answered Sep 18 '22 16:09

Ben


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:
enter image description here

like image 33
DanielZanchi Avatar answered Sep 17 '22 16:09

DanielZanchi