【问题标题】:Cocoa NSTextField change placeholder colorCocoa NSTextField 更改占位符颜色
【发布时间】:2014-08-03 15:51:12
【问题描述】:

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

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: 嗯,它改变了颜色,但是如果文本字段获得焦点,占位符字体变小,很奇怪。

【问题讨论】:

  • 虽然不是很理想,但您始终可以添加一个额外的属性来设置字体(NSFontAttributeName),这将防止占位符文本显示小于预期。
  • 嗨,Lupurus,当占位符获得焦点时,您找到解决较小字体大小的方法了吗?我也有同样的问题。
  • 看到相同并想知道如何修复它,尽管当您不使用设置时占位符会消失@Daniel

标签: cocoa swift


【解决方案1】:

通过显式定义 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

【讨论】:

    【解决方案2】:

    您应该在NSTextFieldCell 而不是NSTextField 中设置占位符文本。

    myTextField.cell.placeholderAttributedString = placeHolderStr
    

    【讨论】:

    • 感谢您的回答,但 NSTextField 中没有 cell 属性
    • @Lupurus 有:NSTextField().cell // NSCell
    【解决方案3】:

    您应该保留当前字体和 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 2012-04-01
      • 2021-09-28
      • 1970-01-01
      • 2017-05-18
      • 2013-02-04
      • 2018-10-29
      • 2018-04-12
      • 2019-10-09
      相关资源
      最近更新 更多