iosswiftuitextfieldnsattributedstringkey

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


Solution

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