swift 4 中的 UITextField attributedPlaceholder 颜色和不透明度

UITextField attributedPlaceholder color and opacity in swift 4

我有自定义的 textField,它有 @IBInspectable 属性 placeHolderColor: UIColor,并且工作正常。我设置为:

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

如何以编程方式仅为此 属性 设置不透明度值,而不是我的文本字段中的普通文本?我没有找到任何匹配项 NSAttributedStringKey 来执行此操作

UIColor class 方法 withAlphaComponent(alpha: ) 设置颜色 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
    }
}

在 Swift 4.2

attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: color.withAlphaComponent(self.alpha)])

SWIFT 5

我用它来更改颜色,而没有为占位符输入新的 String

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