emerog
emerog

Reputation: 79

UITextField attributedPlaceholder color and opacity in swift 4

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

Upvotes: 3

Views: 4628

Answers (2)

Allanguzmanf
Allanguzmanf

Reputation: 55

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"])

Upvotes: 1

AshvinGudaliya
AshvinGudaliya

Reputation: 3314

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)])

Upvotes: 7

Related Questions