Last active
September 15, 2016 23:52
-
-
Save jpmhouston/a6900109474e5930cb5ea972f35455e8 to your computer and use it in GitHub Desktop.
UITextField subclass adding placeholderColor property
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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