Skip to content

Instantly share code, notes, and snippets.

@maximbilan
Created November 23, 2015 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maximbilan/1a6265ffea16b3ca8d17 to your computer and use it in GitHub Desktop.
Save maximbilan/1a6265ffea16b3ca8d17 to your computer and use it in GitHub Desktop.
import Foundation
import UIKit
@objc public class LeftAlignedSearchBar: UISearchBar, UISearchBarDelegate {
override public var placeholder:String? {
didSet {
if #available(iOS 9.0, *) {
if let text = placeholder {
if text.characters.last! != " " {
let attr = UITextField.appearanceWhenContainedInInstancesOfClasses([LeftAlignedSearchBar.self]).defaultTextAttributes
let maxSize = CGSizeMake(self.bounds.size.width - 86, 40)
let widthText = text.boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
let widthSpace = " ".boundingRectWithSize( maxSize, options: .UsesLineFragmentOrigin, attributes:attr, context:nil).size.width
let spaces = floor((maxSize.width - widthText) / widthSpace)
let newText = text + ((Array(count: Int(spaces), repeatedValue: " ").joinWithSeparator("")))
if newText != text {
placeholder = newText
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment