How to display shadow for NSView?

Abh*_*hek 7 macos cocoa calayer nsview swift

I have gone through many threads here and other blogs but not able to solve this issue. I have a added a subview in content view of window. Here is the storyboard--

在此输入图像描述-

I have dragged out outlet of customView to view controller and here is the code for view controller -

import Cocoa
import QuartzCore

class ViewController: NSViewController {

    @IBOutlet weak var customView: NSView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.wantsLayer = true
        self.customView.wantsLayer = true
        self.customView.layer?.backgroundColor = NSColor.redColor().CGColor
        self.customView.layer?.cornerRadius = 5.0
        self.customView.layer?.shadowOpacity = 1.0
        self.customView.layer?.shadowColor = NSColor.blackColor().CGColor
        self.customView.layer?.shadowOffset = NSMakeSize(0, -3)
        self.customView.layer?.shadowRadius = 20
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

I have added QuartzCore frame work in my project - 在此输入图像描述

But the shadow is not appearing, here is the screen shot - 在此输入图像描述.

I am not able to solve what appears to be trivial. What am I missing? thanks for your help.

Abh*_*hek 18

如果我添加以下行,它解决了问题 -

self.customView.shadow = NSShadow()
Run Code Online (Sandbox Code Playgroud)

最终代码是 -

import Cocoa
import QuartzCore

class ViewController: NSViewController {

    @IBOutlet weak var customView: NSView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.view.wantsLayer = true
        self.view.superview?.wantsLayer = true
        self.customView.wantsLayer = true
        self.customView.shadow = NSShadow()
        self.customView.layer?.backgroundColor = NSColor.redColor().CGColor
        self.customView.layer?.cornerRadius = 5.0
        self.customView.layer?.shadowOpacity = 1.0
        self.customView.layer?.shadowColor = NSColor.greenColor().CGColor
        self.customView.layer?.shadowOffset = NSMakeSize(0, 0)
        self.customView.layer?.shadowRadius = 20
    }

    override var representedObject: AnyObject? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}
Run Code Online (Sandbox Code Playgroud)

我无法确定问题可能是这里有人会指出它.

  • NSShadow()是关键.接下来托管视图(例如superview)需要wantsLayer为true. (2认同)