我尝试更改占位符文本的颜色。该代码不起作用:
let color = NSColor.redColor()
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
myTextField.placeholderAttributedString = placeHolderStr
Run Code Online (Sandbox Code Playgroud)
我得到了错误-[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance。有什么想法,我该如何更改占位符的颜色?
更新:这有效:
(myTextField.cell() as NSTextFieldCell).placeholderAttributedString = placeHolderStr
Run Code Online (Sandbox Code Playgroud)
更新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
Run Code Online (Sandbox Code Playgroud)
以下是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
Run Code Online (Sandbox Code Playgroud)
您应该将占位符文本设置为NSTextFieldCell而不是NSTextField。
myTextField.cell.placeholderAttributedString = placeHolderStr
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3493 次 |
| 最近记录: |