Search code examples
swiftmacoscocoanstextfield

Backgroundcolor of NSTextfield


I use a NSTextfield as a label. I try to change backgroundColor like this

let myLabel = NSTextField(labelWithString: "A Label")
myLabel.backgroundColor = NSColor.green

But it does not work. What´s going wrong?


Solution

  • You need to set drawsBackground of your NSTextField to true. This boolean controls whether the receiver’s cell draws its background color behind its text.

    let myLabel = NSTextField(labelWithString: "A Label")
    myLabel.drawsBackground = true
    myLabel.backgroundColor = NSColor.green
    

    From Apple Documentation:

    In order to prevent inconsistent rendering, background color rendering is disabled for rounded-bezel text fields.