簡體   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