swiftcocoanstextviewnsvisualeffectview

Add a NSVisualEffectView below NSTextView


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

Solution

  • 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.