Cocoa NSTextField 更改占位符颜色

9

我试图更改占位文本的颜色。以下代码不起作用:

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: 嗯,它改变了颜色,但如果文本字段获得焦点,占位符字体大小会变小,非常奇怪。


虽然不是最理想的方法,但你可以添加一个额外的属性来设置字体(NSFontAttributeName),这将防止占位文本显示得比预期更小。 - Andy Shephard
1
嗨,Lupurus,你找到了当占位符获得焦点时字体变小的解决方案吗?我也遇到了同样的问题。 - Daniel
看到相同的问题并想知道如何解决,尽管当您不调整设置时占位符会消失 @Daniel - ctietze
3个回答

11

通过明确定义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

1
你应该在 NSTextFieldCell 中设置占位文本而不是 NSTextField
myTextField.cell.placeholderAttributedString = placeHolderStr

谢谢您的回答,但是 NSTextField 没有 cell 属性。 - Lupurus
@Lupurus 这里有:NSTextField().cell // NSCell - Sentry.co

0

你应该保留当前字体和从IB获取的当前值

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接