繁体   English   中英

Cocoa NSTextField更改占位符颜色

[英]Cocoa NSTextField change placeholder color

我尝试更改占位符文本颜色。 此代码不起作用:

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

你应该保留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
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM