Thank Hello, this is TOSH. When using UITextField, there are many people who feel that textColor can be set as it is, but for some reason the color of placeHolder cannot be set as it is. So, I thought about an extension that can be set for placeHolder in the same way as TextColor.
Normally, if you want to change the color of placeHolder,
let color: UIColor = ~Specify any color here~
textField.attributedPlaceholder = NSAttributedString(
string: "Characters in placeHolder",
attributes: [NSAttributedString.Key.foregroundColor : color])
Well, it's not that hard, but it's like using NSAttibutedString.
extension UITextField {
var placeHolderColor: UIColor {
set {
self.attributedPlaceholder = NSAttributedString(
string: self.placeholder ?? "",
attributes: [NSAttributedString.Key.foregroundColor : newValue])
}
get {
let defaultPlaceHolderGray = UIColor(red: 0, green: 0, blue: 0.0980392, alpha: 0.22)
guard self.attributedPlaceholder?.length != 0,
let placeHolderColor = self.attributedPlaceholder?.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? UIColor else {
return defaultPlaceHolderGray
}
return placeHolderColor
}
}
}
Stored Property cannot be used in extension, so Computed Property is used. The setter is easy, but the one that struggled unexpectedly was the getter. It is possible that there are no characters in the Place Holder, so you need to guard with self.attributedPlaceholder? .Length! = 0. Also, since it only takes the first character of attributedPlaceholder, if you encounter an AttributedString whose character changes after the first character, you can think that it is not working well. However, even if it is set, it seems that it will not be fetched easily, so I feel that I do not have to think too much about this. .. ..
What I noticed while implementing it is that I set the color of Place Holder in the first place, but it does not mean that I do not set the contents, so I am using NSAttributedString which can be done at the same time as setting text. thought. (In the case of Text, the user inputs characters, so the main usage is to specify the color in the initial state and not specify Text) So it's okay to make it, but it feels like it's an extension that isn't often used.
Recommended Posts