3

I have custom textField which has @IBInspectable property placeHolderColor: UIColor and it works fine. I set it by:

attributedPlaceholder = NSAttributedString(string: placeHolder, attributes:[NSAttributedStringKey.foregroundColor: placeHolderColor])

How can I set programmatically an opacity value for this property only, not for normal text in my textfield ? I didn't find any matching NSAttributedStringKey to do this

emerog
  • 69
  • 3
  • 10

2 Answers2

7

UIColor class methods withAlphaComponent(alpha: ) to set a color alpha. read more

@IBInspectable var placeholderTextColor: UIColor? {
    set {
        guard let color = newValue else { return }

        let placeholderText = self.placeholder ?? ""
        attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor: color.withAlphaComponent(alpha: self.alpha)])
    }
    get{
        return self.placeholderTextColor
    }
}

in Swift 4.2

attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: color.withAlphaComponent(self.alpha)])
AshvinGudaliya
  • 3,234
  • 19
  • 37
  • In Swift 4.2.1 the answer above will prompt "Type 'NSAttributedStringKey' (aka 'NSString') has no member 'foregroundColor'". Instead, try: attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: color.withAlphaComponent(alpha: self.alpha)]) Taken from: https://stackoverflow.com/a/50325874/2854529 – Got99Errors Nov 04 '18 at 12:17
1

SWIFT 5

I used this to change the color without inputing a new String for placeholder

textField.attributedPlaceholder =  NSAttributedString(string: textField.text!, attributes:
[NSAttributedString.Key.foregroundColor: UIColor."Your preferred color"])