Add a NSVisualEffectView below NSTextView

832 Views Asked by At

I want to add a NSVisualEffectView inside my NSTextView, however when I add it, the text is below the NSVisualEffectView, so, how can i add the NSVisualEffectView below the text?

My code for OS X:

class myTextView: NSTextView {

    override func awakeFromNib() {
        let visualEffectView = NSVisualEffectView(frame: NSMakeRect(20, 20, 30, 18))
        visualEffectView.material = NSVisualEffectMaterial.Dark
        visualEffectView.blendingMode = NSVisualEffectBlendingMode.BehindWindow
        self.addSubview(visualEffectView)
    }
}
2

There are 2 best solutions below

2
On BEST ANSWER

Maybe this will help you:

class MyTextView: NSTextView {

    lazy var visualEffectView: NSVisualEffectView = {
        let visualEffectView = NSVisualEffectView()
        visualEffectView.material = NSVisualEffectMaterial.Dark
        visualEffectView.blendingMode = NSVisualEffectBlendingMode.BehindWindow

        return visualEffectView
    }()

    override func awakeFromNib() {
        super.awakeFromNib()

        self.drawsBackground = false
    }

    override func viewDidMoveToSuperview() {
        super.viewDidMoveToSuperview()

        if let containerView = self.superview?.superview?.superview {
            containerView.addSubview(self.visualEffectView, positioned: .Below, relativeTo: self)
        }
    }

    override func resizeSubviewsWithOldSize(oldSize: NSSize) {
        super.resizeSubviewsWithOldSize(oldSize)

        if let superview = self.superview?.superview {
            self.visualEffectView.frame = superview.frame
        }
    }

}

It's a text view in a scroll view and clip view so you have to get its superview.

2
On
self.sendSubviewToBack(visualEffectView)

But the visual effect needs to be applied to the parent container, not the text view itself, so if I'm understanding your code correctly you need to move this whole thing up to whatever the parent view is.