0

My NSTextField has rounded corners and a white background color, but it seems as though the view itself is rectangular. This means the space between the rounded corners and the bounding rectangle are showing as transparent. How can I fill in this area so that it doesn't stand out?

Image:

The NSTextField with terrible corners.

Code:

let textFieldLayer = CALayer()
textField.layer = textFieldLayer
textField.backgroundColor = NSColor.whiteColor()
textField.layer?.backgroundColor = NSColor.whiteColor().CGColor
textField.layer?.borderColor = NSColor(calibratedRed: 47/255.0, green: 146/255.0, blue: 204/255.0, alpha: 1.0).CGColor
textField.layer?.borderWidth = 1
textField.layer?.cornerRadius = 7
user3225395
  • 581
  • 6
  • 23

2 Answers2

0

I did it by subclassing NSTextField and overriding its drawRect method:

override func drawRect(dirtyRect: NSRect) {
    super.drawRect(dirtyRect)
    var bounds: NSRect = self.bounds
    var border: NSBezierPath = NSBezierPath(roundedRect: NSInsetRect(bounds, 0.5, 0.5), xRadius: 3, yRadius: 3)
    NSColor(red: 47 / 255.0, green: 146 / 255.0, blue: 204 / 255.0, alpha: 1.0).set()
    border.stroke()
}
rocky
  • 3,521
  • 1
  • 23
  • 31
  • 1
    This is a decent way to solve the original issue, although if a focus ring is used then it suffers a similar issue; it's an easy fix though if you override it. – l'L'l Jul 19 '16 at 00:34
0

I know this is old, but in case others are here looking. I found this post on Medium to be a huge help when customizing an NSTextField. This utilizes the textfield's CALayer. Here's a snippet from the link for the relevant bit:

override fun viewDidLoad() {
super.viewDidLoad()
inputTextField.wantsLayer = true
let textFieldLayer = CALayer()
inputTextField.layer = textFieldLayer
inputTextField.backgroundColor = fieldBackgroundColor
inputTextField.layer?.backgroundColor = fieldBackgroundColor.cgColor
inputTextField.layer?.borderColor = fieldBorderColor.cgColor
inputTextField.layer?.borderWidth = 1
inputTextField.layer?.cornerRadius = 5
inputTextField.textColor = fieldTextColor
}

Also note that if you've futzed around with NSTextField's default settings in IB you may not get the hoped for results. I discovered that this approach did not work correctly if the border selection was anything other than the first option:

Only the first will do.

Schuuure
  • 301
  • 2
  • 10