简体   繁体   中英

Cocoa NSTextField change placeholder color

I try to change the placeholder text color. This code doesn't work:

let color = NSColor.redColor()
let attrs = [NSForegroundColorAttributeName: color]
let placeHolderStr = NSAttributedString(string: "My placeholder", attributes: attrs)
myTextField.placeholderAttributedString = placeHolderStr

I get the error -[NSTextField setPlaceholderAttributedString:]: unrecognized selector sent to instance . Any ideas, how I can change the color of the placeholder?

UPDATE: This works:

(myTextField.cell() as NSTextFieldCell).placeholderAttributedString = placeHolderStr

UPDATE 2: Hmm, it changes the color, but if the text field gets the focus, the placeholder font size get's smaller, very strange.

By explicitly defining the font of the NSAttributedString, the placeholder font resizing referred to in the original question is fixed.

The following is a working example in 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

The following is a working example in 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

You should keep current font, and current value from 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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