3

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

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

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

4

2 回答 2

7

UIColorwithAlphaComponent(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
    }
}

在斯威夫特 4.2

attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedString.Key.foregroundColor: color.withAlphaComponent(self.alpha)])
于 2017-12-26T18:40:54.250 回答
1

斯威夫特 5

我用它来改变颜色而不输入新String的占位符

textField.attributedPlaceholder =  NSAttributedString(string: textField.text!, attributes:
[NSAttributedString.Key.foregroundColor: UIColor."Your preferred color"])
于 2020-05-25T20:19:34.370 回答