Cocoa NSTextField改变占位符颜色



我尝试改变占位符文本的颜色。这段代码不起作用:

let color = NSColor.redColor()
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
myTextField.placeholderAttributedString = placeHolderStr

我得到错误-[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance。有什么主意吗,我怎样才能改变占位符的颜色?

更新:如此:

(myTextField.cell() as NSTextFieldCell).placeholderAttributedString = placeHolderStr

更新2:嗯,它改变了颜色,但是如果文本框成为焦点,占位符字体就变小了,很奇怪

通过显式定义NSAttributedString的字体,原来问题中提到的占位符字体大小调整是固定的。

下面是Swift 3.0中的一个工作示例:

let color = NSColor.red
let font = NSFont.systemFont(ofSize: 14)
let attrs = [NSForegroundColorAttributeName: color, NSFontAttributeName: font]
let placeholderString = NSAttributedString(string: "My placeholder", attributes: attrs)
(textField.cell as? NSTextFieldCell)?.placeholderAttributedString = placeholderString

下面是Swift 4.2中的一个工作示例:

let attrs = [NSAttributedString.Key.foregroundColor: NSColor.lightGray,
             NSAttributedString.Key.font: NSFont.systemFont(ofSize: 14)]
let placeholderString = NSAttributedString(string: "My placeholder", attributes: attrs)
(taskTextField.cell as? NSTextFieldCell)?.placeholderAttributedString = placeholderString

您应该在NSTextFieldCell而不是NSTextField中设置占位符文本。

myTextField.cell.placeholderAttributedString = placeHolderStr

应该保持当前字体和当前值

  extension NSTextField {
    func setHintTextColor (color: NSColor) {
        let currentHint = placeholderString ?? ""
        let placeholderAttributes: [NSAttributedString.Key: Any] = [
            NSAttributedString.Key.foregroundColor: color,
            NSAttributedString.Key.font: font!
        ]
        let placeholderAttributedString = NSMutableAttributedString(string: currentHint, attributes: placeholderAttributes)
        let paragraphStyle = NSMutableParagraphStyle()
        placeholderAttributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0,length: placeholderAttributedString.length))
        self.placeholderAttributedString =  placeholderAttributedString
    }
}

最新更新