How to left align UISearchBar placeholder text
Based in Mohittomar answer, as asked by @DevC to add spaces to the end of the place holder, here the code in swift:
I subclass placeholder in the UISearchBar, after set the value, I check if the last character is a space. then get the size of one space and how many spaces I need to add to align left.
class SearchBar: UISearchBar, UISearchBarDelegate {
override var placeholder:String? {
didSet {
if let text = placeholder {
if text.last != " " {
// get the font attribute
let attr = UITextField.s_appearanceWhenContainedIn(SearchBar).defaultTextAttributes
// define a max size
let maxSize = CGSizeMake(UIScreen.mainScreen().bounds.size.width - 60, 40)
// get the size of the text
var widthText = text.boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
// get the size of one space
var widthSpace = " ".boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
let spaces = floor((maxSize.width - widthText) / widthSpace)
// add the spaces
let newText = text + (" " * spaces)
// apply the new text if nescessary
if newText != text {
placeholder = newText
}
}
}
}
}
Don't use a UISearchBar
if you need to do these kinds of customizations. You'll have to make your own using a UITextField
and a UIImageView
, and responding to the delegate calls.