-1

I have a label in a macOS project which when connected becomes an NSTextField. I want to make the text have a gradient overlay.

I have some code to do this with an iOS UIButton, but for this project I keep getting the error that NSView has no such thing called mask and I don't know what to mask it to

extension NSTextField {
func applyGradientText(colors: [CGColor]) {
    let gradient = CAGradientLayer()
    gradient.frame = bounds
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.colors = colors
    layer?.insertSublayer(gradient, at: 0)
    let overlayView = NSView(frame: bounds)
    overlayView.layer?.insertSublayer(gradient, at: 0)

overlayView has nothing called mask, and I don't know what to mask to

    overlayView.mask = SOMETHING

    addSubview(overlayView)
  }
}
koen
  • 5,383
  • 7
  • 50
  • 89
Levi K
  • 573
  • 1
  • 4
  • 23

1 Answers1

0

You need to call wantsLayer = true on the NSTextField as it doesn't have a layer by default. Then just set layer?.mask = gradient and the label will show where gradient is CGColor.clear.

label.applyGradientText(colors: [CGColor.black, CGColor.clear])

extension NSTextField {
    func applyGradientText(colors: [CGColor]) {
        let gradient = CAGradientLayer()
        gradient.frame = bounds
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.colors = colors
        wantsLayer = true
        layer?.mask = gradient
    }
}

Does this do what you want?

Loengard
  • 401
  • 2
  • 7
  • Hey @Leongard thanks for the answer, but the problem is that the layer doesn't have a variable called mask – Levi K Aug 20 '19 at 20:34
  • @Levi K Really? label doesn't have mask but label.layer should. It's a plain CALayer. Does my extension above give you an error on layer?.mask = gradient? Works for me. – Loengard Aug 21 '19 at 07:52
  • @Leongard It did the last time I tried, but I just cleaned it, so I'll try again and let you know – Levi K Aug 21 '19 at 23:46