
I need to make a custom search bar like this. Th
SWIFT 3
swift 3 does not allow to override placeholder property. This is the modified version of Drix answer.
func setPlaceHolder(placeholder: String)-> String
{
var text = placeholder
if text.characters.last! != " " {
// define a max size
let maxSize = CGSize(width: UIScreen.main.bounds.size.width - 97, height: 40)
// let maxSize = CGSizeMake(self.bounds.size.width - 92, 40)
// get the size of the text
let widthText = text.boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:nil, context:nil).size.width
// get the size of one space
let widthSpace = " ".boundingRect( with: maxSize, options: .usesLineFragmentOrigin, attributes:nil, context:nil).size.width
let spaces = floor((maxSize.width - widthText) / widthSpace)
// add the spaces
let newText = text + ((Array(repeating: " ", count: Int(spaces)).joined(separator: "")))
// apply the new text if nescessary
if newText != text {
return newText
}
}
return placeholder;
}
and call the function as :
searchBar.placeholder = self.setPlaceHolder(placeholder: "your placeholder text");