圆形NSTextField绘制透明角落?

时间:2016-07-18 03:40:37

标签: swift macos cocoa interface-builder nstextfield

我的NSTextField有圆角和白色背景颜色,但看起来好像视图本身是矩形的。这意味着圆角和边界矩形之间的空间显示为透明。如何填写此区域以使其不突出?

图像:

The NSTextField with terrible corners.

代码:

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

2 个答案:

答案 0 :(得分:0)

我是通过继承NSTextField并覆盖其drawRect方法来实现的:

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()
}

答案 1 :(得分:0)

我知道这是旧的,但万一其他人在这里寻找。在自定义NSTextField时,我在Medium上发现this post是一个巨大的帮助。这利用了textfield的CALayer。以下是相关位链接的摘录:

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
}

另请注意,如果您在IB中使用NSTextField的默认设置,则可能无法获得所希望的结果。我发现如果边框选择不是第一个选项,这种方法无法正常工作:

Only the first will do.