Cocoa NSTextField 更改占位符颜色

标签 cocoa swift

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

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

关于Cocoa NSTextField 更改占位符颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25106372/

相关文章:

objective-c - NSSavePanel 未保存在桌面上?

macos - Mac 上的 EventKit 和应用程序扩展

cocoa - NSApp的keyWindow是什么时候创建的?

android - ios相当于android xml的是什么?

ios - 在所有 View Controller 中隐藏状态栏 - IOS

ios - 如何在 Swift 中使用 SKAction 的执行方法

cocoa - 如何检查 NSData 对象是否包含子 NSData?

objective-c - Objective-C 中的 NSBundle 沙箱

ios - SWIFT uiviewcontroller 初始化

swift - 在 Swift 2 中,禁用 NSMenuItem 的正确方法是什么?