Skip to content

Instantly share code, notes, and snippets.

@jpmhouston
Last active September 15, 2016 23:52
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 jpmhouston/a6900109474e5930cb5ea972f35455e8 to your computer and use it in GitHub Desktop.
Save jpmhouston/a6900109474e5930cb5ea972f35455e8 to your computer and use it in GitHub Desktop.
UITextField subclass adding placeholderColor property
// TODO: link here to SO post that inspired this
// ^ that source worked fine when setting placeholderColor sometime after
// placeholder or attributedPlaceholder, but not the other way around.
// this is an attempt to fix this, it might work.
class ColorPHTextField : UITextField {
@IBInspectable var placeholderColor: UIColor? {
didSet {
applyPlaceholderColor()
}
}
override var placeholder: String? {
didSet {
//log("set textfield placeholder to \"self.placeholder\"")
if placeholderColor != nil {
applyPlaceholderColor()
}
}
}
override var attributedPlaceholder: NSAttributedString? {
didSet {
//log("set textfield attributed placeholder to \"self.placeholder\"")
if placeholderColor != nil {
applyPlaceholderColor()
}
}
}
private func applyPlaceholderColor() {
let attrString = self.attributedPlaceholder != nil ? NSMutableAttributedString(attributedString: self.attributedPlaceholder!) :
NSMutableAttributedString(string: self.placeholder ?? "")
let wholeRange = NSMakeRange(0, attrString.length)
if let color = placeholderColor {
//log("setting custom color of placeholder \"self.placeholder\" to \(color.hexString(false))")
attrString.setAttributes([NSForegroundColorAttributeName: color], range: wholeRange)
} else {
//log("unsetting custom color of placeholder \"self.placeholder\"")
attrString.removeAttribute(NSForegroundColorAttributeName, range: wholeRange)
}
self.attributedPlaceholder = attrString
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment