swift 4 中的 UITextField 属性占位符颜色和不透明度

eme*_*rog 3 uitextfield ios swift nsattributedstringkey

我有自定义的textField具有@IBInspectable财产placeHolderColor: UIColor和正常工作。我通过以下方式设置:

attributedPlaceholder = NSAttributedString(string: placeHolder, attributes:[NSAttributedStringKey.foregroundColor: placeHolderColor])
Run Code Online (Sandbox Code Playgroud)

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

Ash*_*iya 7

UIColor类方法withAlphaComponent(alpha: )来设置颜色 alpha。阅读更多

@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
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Swift 4.2 中

attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: color.withAlphaComponent(self.alpha)])
Run Code Online (Sandbox Code Playgroud)